考慮遷移如下:
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
和一個模型作爲fol低點:
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
那麼這種形式的代碼應該很好地工作(我剛下的Rails 3.0.3進行測試),正確顯示和每次保存/編輯節省時間的美元金額。 (這是使用默認腳手架更新/創建方法)。
<%= form_for(@item) do |f| %>
<div class="field">
<%= f.label :amount %><br />
<%= f.text_field :amount %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
這是1345 。我認爲這個表格正在檢索存儲的值,而不會將其轉換回美元。 – David 2011-01-31 23:36:52
那麼如何將1000轉換爲100而不是顯示1,000?!有什麼地方錯了。其次(我沒有使用金錢寶石),但我懷疑數量字段的屬性閱讀器不會轉換該值。或者,也許這需要你做,而不是寶石?你發佈的一些代碼將有所幫助。另外,請檢查已加載的記錄並查看金額字段的值。 – Zabba 2011-01-31 23:40:20
對不起,這是一個錯字。它預先填充爲1000. – David 2011-02-01 00:09:31