2011-01-31 66 views
8

我遇到了表单和money gem问题。Rails钱宝石和表单生成器

这是我的问题:

  1. 我创造出具有“数量”字段(映射到钱的对象)的记录。假设我输入10(美元)。
  2. 钱宝石将其转换为1000(美分)
  3. 我编辑同一记录和形式的预填充量字段1000
  4. 如果我保存记录不改变任何东西,它会转换成1000(美元)至100000(美分)

如何使其显示以美元而不是美分计算的预填充金额?

编辑:

我试图编辑这样的_form.html:

= f.text_field(:amount, :to_money) 

,我得到这个错误:

undefined method `merge' for :to_money:Symbol 
+0

这是1345 。我认为这个表格正在检索存储的值,而不会将其转换回美元。 – David 2011-01-31 23:36:52

+0

那么如何将1000转换为100而不是显示1,000?!有什么地方错了。其次(我没有使用金钱宝石),但我怀疑数量字段的属性阅读器不会转换该值。或者,也许这需要你做,而不是宝石?你发布的一些代码将有所帮助。另外,请检查已加载的记录并查看金额字段的值。 – Zabba 2011-01-31 23:40:20

+0

对不起,这是一个错字。它预先填充为1000. – David 2011-02-01 00:09:31

回答

11

考虑迁移如下:

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 %> 
3

如果您的表中有多个货币字段,并且您不能将它们命名为“cents”。

class CreateItems < ActiveRecord::Migration 
    def self.up 
    create_table :items do |t| 
     t.integer :purchase_price_cents 
     t.string :currency 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :items 
    end 
end 

这将模型改为

class Item < ActiveRecord::Base 

    composed_of :purchase_price, 
    :class_name => "Money", 
    :mapping  => [%w(purchase_price_cents cents), %w(currency currency_as_string)], 
    :constructor => Proc.new { |purchase_price_cents, currency| Money.new(purchase_price_cents || 0, currency || Money.default_currency) }, 
    :converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") } 

end 
3

现在,您可以直接编辑货币化领域(钱轨1.3.0):

# add migration 
add_column :products, :price, :price_cents 

# set monetize for this field inside the model 
class Product 
    monetize :price_cents 
end 

# inside form use .price instead of .price_cents method 
f.text_field :price 

https://stackoverflow.com/a/30763084/46039