Forum: Ruby on Rails Validation on composed_of problem

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eduardo R. (Guest)
on 2006-01-22 18:22
I am having problems with this:

    validates_presence_of :amount

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

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

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 topic is locked and can not be replied to.