Validation on composed_of problem

I am having problems with this:

validates_presence_of :amount

validates_format_of :amount, :with => Money::PATTERN, :allow_nil => 


composed_of :amount, :class_name => Money, :mapping => [[:amount, 


The problem is when I use this field in a form, and the text is blank,
ActiveRecord gives me two errors:

“money is invalid”
“money can’t be blank”

I want only “money can’t be blank” if the field is empty, and “money is
invalid” only when the pattern doesn’t match and the field is not empty.

The problem here is that when ActiveRecord run “validates_format_of”, it
calls “model.amount”, which in turn calls “Money.initialize(nil)”. Then
the “amount” field gets an empty Money, which is not blank.

I wrote some custom code to fix that (implemented “def amount=(value)”
and “def amount”), but I would like to know if there is already
something I could do instead of using this custom code.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs