如何正确使用金钱宝石与表单生成器?
我有带有字段price_cents 和price_currency 的产品模型。货币默认货币是美元。
模型:
class Product < ActiveRecord::Base
CURRENCIES = %w(USD EUR)
composed_of :price,
:class_name => "Money",
:mapping => [%w(price_cents cents), %w(price_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 convert #{value.class} to Money") }
end
表单:
= form_for @product do |f|
= f.label :price
= f.text_field :price
= f.select :price_currency, Product::CURRENCIES
= f.submit
控制器 创建方法: @product = Product.new(params[:product])
问题: 例如,当用户将价格字段设置为 100 并将 Price_currency 设置为欧元时,它会使用默认货币(美元)创建价格。我该如何修复它?是否可以在视图中执行此操作,或者我应该在控制器中执行此操作(例如@product.price.currency = ...)?
I have model Product with fields price_cents and price_currency. Money default currency is USD.
Model:
class Product < ActiveRecord::Base
CURRENCIES = %w(USD EUR)
composed_of :price,
:class_name => "Money",
:mapping => [%w(price_cents cents), %w(price_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 convert #{value.class} to Money") }
end
Form:
= form_for @product do |f|
= f.label :price
= f.text_field :price
= f.select :price_currency, Product::CURRENCIES
= f.submit
Controller Create method: @product = Product.new(params[:product])
Problem: When user sets price field to 100 for example and price_currency to EUR it creates price using default currency(USD). How I can fix it? Is it possible to do it in view or i should do it in controller (e.g. @product.price.currency = ...)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我有同样的问题。 使用 Money gem 的表单选择设置货币
通过添加解决了这个问题create 方法中的一行。检查上面的线程,让我知道您在这方面需要进一步的帮助。
I had the same issue. Setting currency with form select with Money gem
Solved it by adding one line in the create method. Check the thread above, and let me know i you need further help on this one.