Ruby on Rails (Money.gem 2.3.* and later)

semmons99 edited this page Apr 9, 2012 · 3 revisions

Use the #composed_of helper to let Active Record deal with embedding the money object in your models. The following example requires a cents and a currency field.

composed_of :price,
  :class_name => "Money",
  :mapping => [%w(cents cents), %w(currency currency_as_string)],
  :constructor => { |cents, currency| || 0, currency || Money.default_currency) }

Also, because the currency attribute is not a simple String but a Money::Currency object, you need a small tweak to make it work.

Extend/hack the Money class with two additional methods:

# You can put this file in the config/initializers/ folder
class Money
  def currency_as_string

  def currency_as_string=(value)
    # WARNING: this method might cause data inconsistency.
    # See
    # currency = Currency.wrap(value)