我遇到了表单和money gem的问题。
这是我的问题:
如何以美元而不是美分显示预先填充的金额?
编辑:
我尝试像这样编辑_form.html:
= f.text_field(:amount, :to_money)
我收到此错误:
undefined method `merge' for :to_money:Symbol
答案 0 :(得分: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
一个模型如下:
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 %>
答案 1 :(得分:3)
如果您的表中有多个货币字段,并且您无法将它们全部命名为“分”。
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
答案 2 :(得分:3)
您现在可以直接编辑货币化的字段(money-rails 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
答案 3 :(得分:0)
简单的货币化方法,步骤如下:
add_monetize:table,:amount
获利:amount_cents,allow_nil:true,数值:{greater_than:0}
params.require(:model).permit(:amount)
保存时,它将以美分保存在db的amount_cents列中