theapokalypsis
theapokalypsis

Reputation: 136

Using money-rails: How to manually set an attribute's currency

I'm currently using:

Use case

I'm updating a money type attribute called dollars_per_month, which I created with the money-rails migration helpers (i.e 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 USD" OR "500" OR "500 CAD" in a text field, and have it save properly. Currently, when a non-global currency is specified, it throws the exception:

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

Which makes sense- I can understand why this is naturally enforced.

However.. I want to forcibly change the currency without caring about such enforcements because this field is merely there for capturing the answer to a question.

The simple solution (despite the future lack of convenience) is to turn this into plain text. However, I am wondering if it is possible to do this with RubyMoney and/or money-rails without touching the rest of the app.

Notes

Appreciate any insights or experience anyone has to share!

Upvotes: 5

Views: 2692

Answers (1)

okeen
okeen

Reputation: 3996

Use the option with_model_currency:

monetize :dollars_per_month_cents, allow_nil: true, with_model_currency: :dollar_per_month_currency

Upvotes: 2

Related Questions