Skip to content

Ruby on Rails (Money.gem 3.0.3 and later)

semmons99 edited this page Sep 12, 2010 · 14 revisions

Use the #compose_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.

class ProductUnit < ActiveRecord::Base
  belongs_to :product
  composed_of :price, :class_name => "Money", :mapping => [%w(cents cents), %w(currency currency_as_string)]

  private
    validate :cents_not_zero

    def cents_not_zero
      errors.add("cents", "cannot be zero or less") unless cents > 0
    end

    validates_presence_of :sku, :currency
    validates_uniqueness_of :sku
end
Clone this wiki locally