Given the migration as follows:
class CreateItems < ActiveRecord::Migration def self.up create_table :items do |t| t.integer :cents t.string :currency t.timestamps end end def self.down drop_table :items end end
And the model as follows:
class Item < ActiveRecord::Base composed_of :amount, :class_name => "Money", :mapping => [%w(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 conver #{value.class} to Money") } end
Then this form code should work fine (I just tested under Rails 3.0.3), correctly displaying and saving the dollar amount every time I save / edit. (This uses the default update / create methods for scaffolds).
<%= form_for(@item) do |f| %> <div class="field"> <%= f.label :amount %><br /> <%= f.text_field :amount %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
Dylan markow
source share