Using lambda or proc and rails-money

I want to be able to dynamically set the currency in the model using the currency set by the model's parent.

Same:

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

event.edition.currency returns the character from the parent model ... e.g .: GBP

But that will not work. Default standard:

 monetize :bonus_cents, :with_currency => :gbp 

Which works great ... any ideas?

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

+6
source share
1 answer

Try the following:

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

I have not tested it completely, but it seems to work.

 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> 
+2
source

Source: https://habr.com/ru/post/949357/


All Articles