Ruby on rails RubyonRails金钱宝石:从表单创建金钱
我是Rails的新手,这是我第一次使用money git。我在模型中插入了以下代码,如money gem wiki中所述:Ruby on rails RubyonRails金钱宝石:从表单创建金钱,ruby-on-rails,ruby,gem,Ruby On Rails,Ruby,Gem,我是Rails的新手,这是我第一次使用money git。我在模型中插入了以下代码,如money gem wiki中所述: composed_of :cash, :class_name => "Money", :mapping => [%w(amount cents), %w(currency currency_as_string)], :constructor => Proc.new { |cents, currency| Money.new(cents || 0, curr
composed_of :cash,
:class_name => "Money",
:mapping => [%w(amount 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 convert #{value.class} to Money") }
在我的数据库中有两个字段:金额整数和货币字符串
我还有一个表单,用户可以输入一定的现金金额:
<%= f.number_field :amount %>
这里的问题是,用户填写的金额是1,50美分,而不是150美分。在将1,50的用户输入插入数据库之前,将其转换为150的最佳方法是什么
问候,,
Gerwin将逗号替换为点,解析为浮点并乘以100
("1,50".gsub(',', '.').to_f * 100).to_i
# => 150
有几个选项可用 在所有情况下,如果输入的货币不是Money.default\u currency中定义的默认货币,则需要知道输入值的货币 1使用新的存取器现金 请看类方法Money.from,特别是字符串中的方法Money.from
<%= f.number_field :cash %>
def amount
cents = read_attribute(:amount) || 0
currency = read_attribute(:currency_as_string) || Money.default_currency
Money.new(cents, currency)
end
def amount=(value)
cash = Money.from_string(value)
write_attribute(:amount, cash.cents)
end