forked from RubyMoney/money
-
Notifications
You must be signed in to change notification settings - Fork 0
Ruby on Rails (Money.gem 3.0.3 and later)
semmons99 edited this page Apr 9, 2012
·
14 revisions
Use the `#composed_of` helper to let Active Record deal with embedding the money object in your models. The following example requires a `price_in_cents` and a `currency` field.
composed_of :price,
:class_name => "Money",
:mapping => [%w(price_in_cents cents), %w(currency currency_as_string)],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
Adding a converter Proc to the `#composed_of` allow any string (eg : textfield) to be saved in the model through Money.parse (or String.to_money) if you have a second field with the currency, it will use it to create the Money object.
With the example above, your migration should include the following lines:
...
t.integer :price_in_cents, :default => 0, :null => false
t.string :currency, :null => false
...