Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm currently using:

  • money-rails v0.12.0
  • rails v4.1.6
  • ruby 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!

like image 953
theapokalypsis Avatar asked Nov 01 '22 16:11

theapokalypsis


1 Answers

Use the option with_model_currency:

monetize :dollars_per_month_cents, allow_nil: true, with_model_currency: :dollar_per_month_currency
like image 70
okeen Avatar answered Nov 15 '22 05:11

okeen