On Tuesday 13 May 2008, Krzysztof Wrzalik wrote:> 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?
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 Schuerig
mailto:michael-q5aiKMLteq4b1SvskN2V4Q@public.gmane.org
http://www.schuerig.de/michael/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---