Soft "raise_error_on_money_parsing" behavior triggering validation error
Closed this issue · 1 comments
Hey,
First, thank you very much for this lib/gem.
I started to look at the code, so I found raise_error_on_money_parsing
which is pretty defensive, I'm not an expert in ActiveRecord & validation extension capability, is there any way to get a middle ground which could add a validation error instead of raising an error?
DISCARDED ORIGINAL ISSUE
I came across a very surprising behavior:
Suppose a simple ActiveRecord model Transaction
class Transaction < ApplicationRecord
monetize :amount_cents
end
With a simple migration excluding currency
create_table :transactions, id: :uuid do |t|
t.monetize :amount, currency: { present: false }, null: false
end
At instantiation time, any currency will be implicitly converted to the default currency
Transaction.new({ amount: Money.new(1800, "EUR") })
puts(transaction.amount.currency) # <- is actually USD
I totally understand the default currency mechanism. But I'm surprised by this behavior.
Context:
- This model should only accept USD
- My application might be manipulating other currency without the need of storing them.
- A developer could simply make a mistake.
It's very risky and I would expect a validation error rather than an implicit conversion. What do you think?
I would be very happy to be able to change this, but I'm a rookie when it comes to ruby/rails, so I would need some guidance there. If anyone could point me to the lines responsible for that, I could do the reverse engineering & try a fix.
@ludofleury I really like this direction, I think implicit currency conversion can be potentially unsafe and should be turned off by default. You should be able to add a new validation rule to the lib/money-rails/active_model/validator.rb
and fail on currency mismatch. Please tell me if you need more help in implementing it