我有包含 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
Controller 创建方法:@product = Product.new(params[:product])
问题:例如,当用户将 price 字段设置为 100 并将 price_currency 设置为 EUR 时,它会使用默认货币(美元)创建价格。我该如何解决?是否可以在 View 中进行,或者我应该在 Controller 中进行(例如@product.price.currency = ...)?
最佳答案
我遇到过同样的问题。 Setting currency with form select with Money gem
通过在 create 方法中添加一行来解决它。检查上面的线程,让我知道你需要关于这个的进一步帮助。
关于ruby-on-rails - 如何正确使用带有表单生成器的货币 gem ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7922816/