ruby-on-railsrubymodelmongoidmoney-rails

Using money-rails with mongoid: How to set currency per model instance


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?


Solution

  • 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: