Using Money Relays: How to Manually Set Attribute Currency

I am currently using:

  • money rails v0.12.0
  • rails v4.1.6
  • ruby v2.1.3

Use case

I am updating an attribute of the type of money called dollars_per_month that I created using the money-rails migration assistants ( add_money ).

So, in my model, I have:

 monetize :dollars_per_month_cents, allow_nil: true 

And my current schema has:

 t.integer "dollars_per_month_cents" t.string "dollars_per_month_currency", default: "CAD", null: false 

Currency is set globally in config / initializers:

 config.default_currency = :cad 

Question

I want the user to be able to enter "500 dollars" OR "500" or "500 CAD" in the text box and save it correctly. Currently, when a non-global currency is indicated, it throws an exception:

 RuntimeError: Can't change readonly currency 'CAD' to 'USD' for field 'dollars_per_month' 

What makes sense - I can understand why this is naturally applied.

However, I want to forcibly change the currency without worrying about such forced actions, because this field is just to answer the question.

A simple solution (despite the lack of future convenience) is to turn this into plain text. However, I am wondering if this can be done using RubyMoney and / or cash rails without touching the rest of the application.

Notes

  • I tried to change dollars_per_month_currency and save the model, however dollars_per_month still returns a CAD based Money object.

  • I looked at instances in the readme currency rails. Although I believe that I can do this work, I feel that it is crowded because it requires additional currency fields .. when I just want to change dollars_per_month_currency .

Appreciate any ideas or experience someone should share!

+5
source share
1 answer

Use the with_model_currency parameter:

 monetize :dollars_per_month_cents, allow_nil: true, with_model_currency: :dollar_per_month_currency 
+2
source

Source: https://habr.com/ru/post/1203239/


All Articles