0

I'm currently using:

money-rails v1.12 rails v6 mongoid v7

I would like to set the default currency to be used by each model instance.

I have set the field in my model like below

field :price, type: Money, with_model_currency: :currency

But when I try to create or fetch records I get this error

Mongoid::Errors::InvalidFieldOption
message:
  Invalid option :with_model_currency provided for field :price.

How do I use the with_model_currency option in a rails mongoid application? How else can I handle money in a rails mongoid application?

Jatto_abdul
  • 109
  • 2
  • 11

1 Answers1

2

When you use type: Money in a mongoid field, you're indicating that the field should be serialized / deserialized with that class in particular. RubyMoney includes methods for serializing to mongo. with_model_currency is not a valid option for the macro field.

You're confusing the method with the money-rails monetize, which DOES have an option named with_model_currency.

In one sentence: drop the with_model_currency: :currency option, it's not available on mongoid fields.

If you want to set a default currency, you will need to do so using Money.default_currency = Money::Currency.new("CAD").

You might also want to write your own serializer (this was not tested):

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

Relevant docs:

cesartalves
  • 1,507
  • 9
  • 18
  • I think it is clear now that `with_model_currency: :currency` is not available in mongoid. However, if I am to use the other option of custom serialization, does this mean I can then update the `currency_iso` field per model instance. Essentially, I would like to see an example of how to create records with custom currency per model instance and reading the price attribute for each instance. – Jatto_abdul Apr 30 '20 at 22:06
  • I will need a bit of time to have a working example in hands. Have you figured out this issue by yourself yet? In short, yes, you'll be able to set whatever currency_iso as you want, because you will be passing a Money object instance to Mongoid. That snippet I presented merely serializes / deserializes the object for you. – cesartalves May 19 '20 at 12:23