4
我有模型產品與字段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 [:產品])
問題:當用戶設置價格字段以100爲例,price_currency到EUR它使用默認貨幣(USD)創建價格。我如何解決它?是否有可能在視圖中執行,或者我應該在控制器中執行它(例如@ product.price.currency = ...)?