加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何正确使用money gem和表单构建器?

发布时间:2020-12-17 02:00:26 所属栏目:百科 来源:网络整理
导读:我有型号产品,字段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_stri
我有型号产品,字段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])

问题:当用户将price字段设置为100并将price_currency设置为EUR时,它会使用默认货币(USD)创建价格.我该怎么办呢?是可以在视图中执行它还是我应该在控制器中执行它(例如@ product.price.currency = …)?

解决方法

我遇到过同样的问题. Setting currency with form select with Money gem

通过在create方法中添加一行来解决它.检查上面的主题,让我知道你需要进一步的帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读