Adding validations on the fly

Hello,

In some situations I’d like to extend single objects with additional
virtual attributes and validation methods for them, for example:

@foo = Foo.find(param[:id])

class << @foo
def bar
nil
end

validates_presence_of :bar
end

puts @foo.valid?

However, what is puzzling is that this still returns true… Can anyone
point me at what I’m doing wrong?

On Tuesday 13 May 2008, Krzysztof Wrzalik wrote:

end

validates_presence_of :bar
end

puts @foo.valid?

However, what is puzzling is that this still returns true… Can
anyone point me at what I’m doing wrong?

Your call to validates_presence_of addss a validation on the singleton
class of @foo where it will never be executed. You’d need to add the
validation to the class Foo

@foo.class.validates_presence_of :bar

but then it would be active for all instances of Foo in the same
process. Much better to add the validation to the class proper and
guard it with a condition

class Foo < ActiveRecord::Base
validates_presence_of :bar, :if => …
end

Michael


Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/