Reputation: 136
I'm currently using:
v0.12.0
v4.1.6
v2.1.3
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
I've tried changing dollars_per_month_currency
and saving the model, however, dollars_per_month
still returns a CAD based Money object.
I've looked into Instance Currencies in the money-rails readme. While I believe I could make this work, I feel it is overkill because it requires extra currency fields.. when I just want to change dollars_per_month_currency
.
Appreciate any insights or experience anyone has to share!
Upvotes: 5
Views: 2692
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