我目前正在使用。
money-rails v1.12rails v6mongoid v7。
我想设置每个模型实例使用的默认货币。
我在模型中设置了如下字段
field :price, type: Money, with_model_currency: :currency
但当我尝试创建或获取记录时,我得到了这个错误信息
Mongoid::Errors::InvalidFieldOption
message:
Invalid option :with_model_currency provided for field :price.
如何使用 with_model_currency
如何在rails mongoid应用程序中处理货币? 我还可以在rails mongoid应用程序中处理货币?
当你使用type: Money时,你表示该字段应该被序列化,特别是该类的反序列化。RubyMoney包含了向mongo序列化的方法。with_model_currency
不是宏的有效选项 field
.
你把方法和钱轨搞混了。monetize
的选项,其中有一个名为 with_model_currency
.
一句话:放下 with_model_currency: :currency
选项,它在 mongoid 字段中不可用。
如果你想设置一个默认的货币,你将需要通过使用 Money.default_currency = Money::Currency.new("CAD")
.
你可能还想写自己的序列化器(这个没有测试)。
class MoneySerializer
class << self
def mongoize(money)
money.to_json
end
def demongoize(json_representation)
money_options = JSON.parse json_representation
Money.new(money_options['cents'], money_options['currency_iso']
end
def evolve(object)
mongoize object
end
end
end
field :price, type: MoneySerializer
相关文档。