考虑迁移如下:
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