0

我目前正在使用:

money-rails v1.12 rails v6 mongoid 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 应用程序中处理资金?

4

1 回答 1

2

当您在 mongoid 字段中使用 type: Money 时,您表示该字段应特别使用该类进行序列化/反序列化。RubyMoney 包括序列化为 mongo 的方法。with_model_currency不是宏的有效选项field

您将该方法与 money-rails 混淆了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

相关文档:

于 2020-04-30T13:46:18.480 回答