使用lambda或proc并跟踪货币



我希望能够使用模型父级设置的货币动态设置模型上的货币。

像这样:

class Event < ActiveRecord::Base
  belongs_to :edition
  monetize :price_cents, :with_currency => proc { |event| event.edition.currency }

event.edition.currency从模型的父级返回一个符号。。。例如:gbp

但它不起作用。默认约定为:

monetize :bonus_cents, :with_currency => :gbp

这很好。。。有什么想法吗?

https://github.com/RubyMoney/money-rails

试试这个:

class Event < ActiveRecord::Base
  belongs_to :edition
  monetize :price_cents
  def currency_for_price
    Money::Currency.find(edition.currency)
  end
end

我没有彻底测试,但它似乎有效。

2.0.0-p195 :012 > Event.new(
                      edition: Edition.new(currency: :gbp),
                      price: 123
                  ).price
 => #<Money fractional:12300 currency:GBP>
2.0.0-p195 :013 > Event.new(
                      edition: Edition.new(currency: :usd),
                      price: 456
                  ).price
 => #<Money fractional:45600 currency:USD>

最新更新