crowdint / acts_as_shopping_cart

Simple Shopping Cart implementation, Official repo: https://github.com/dabit/acts_as_shopping_cart
MIT License
257 stars 88 forks source link

How can I set currency? #30

Closed Daniel254 closed 7 years ago

Daniel254 commented 9 years ago

shopping_cart_item_fields creates column price_currency with default value "USD" in shopping_cart_items How can I set other currency?

jph commented 9 years ago

Same problem here. I tried setting Money's default in environment.rb:

Money.default_currency = Money::Currency.new("CAD")

However my price_currency attribute is still USD when I add an item to a cart.

emaiax commented 9 years ago

@jph @Daniel254 try putting the config bellow in an initializer and let me know if it works.

MoneyRails.configure.default_currency = :cad

https://github.com/RubyMoney/money-rails#configuration-parameters

jph commented 9 years ago

@emaiax that absolutely worked, thanks.

emaiax commented 9 years ago

@jph you're welcome! :)

emaiax commented 9 years ago

@Daniel254 can you close this issue? Tks!

movstox commented 8 years ago

@emaiax I had the same question and added config/initializers/money.rb:

MoneyRails.configure do |config|
  config.default_currency = :gbp
end

However, now, when I add to cart (via rails console), I get an error:

[6] pry(main)> c.add Variant.last, 50
  Variant Load (0.4ms)  SELECT  "variants".* FROM "variants"  ORDER BY "variants"."id" DESC LIMIT 1
  CartItem Load (0.3ms)  SELECT  "cart_items".* FROM "cart_items" WHERE "cart_items"."owner_id" = $1 AND "cart_items"."owner_type" = $2 AND "cart_items"."item_type" = 'Variant' AND "cart_items"."item_id" = 35  ORDER BY "cart_items"."id" ASC LIMIT 1  [["owner_id", 7], ["owner_type", "Cart"]]
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
ActiveRecord::UnknownAttributeError: unknown attribute 'price' for CartItem.

If I comment out initializer, the price method on CartItem is back.

movstox commented 8 years ago

So I think I've found a solution: when you have GBP as a currency, it looks for price_pennies method, not price_cents.

Basically I did 2 things to make everything work:

class TryAddingMoney < ActiveRecord::Migration
  def change
    remove_column :cart_items, :price_currency
    remove_column :cart_items, :price_cents
    add_monetize :cart_items, :price
  end
end 

My CartItem class looks like this now:

  class CartItem < ActiveRecord::Base
    acts_as_shopping_cart_item_for :cart
    # compatibility with GBP currency
    monetize :price_pennies
    def price_cents=(value)
      price_pennies = value
    end

    def price_cents
      price_pennies
    end
  end
emaiax commented 7 years ago

@movstox in https://github.com/RubyMoney/money-rails#configuration-parameters you can set the postfix of the amount column instead of aliasing the attributes.

Let us know if that works.

emaiax commented 7 years ago

@Daniel254 please, close the issue. Thanks!