使用lambda或proc和rails-money

时间:2013-07-13 09:06:10

标签: ruby-on-rails lambda ruby-on-rails-4 ruby-2.0 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

1 个答案:

答案 0 :(得分:2)

试试这个:

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>