Validation conditions on-the-fly
I wanted to validate a child model only if the parent model specifies a specific condition, so I tried this:
validates :attr, presence: true, if: self.foo.baz(:condition)
Rails complained that foo is undefined for the object, even though I built it.
Apparently the validations are generated statically and will not accept on-the-fly conditions i.e. accessing parent class methods.
To generate conditions only after the object is instantiated,I found out that I have to do this:
validates :attr, presence: true, if: lambda{ |p| p.foo.baz(:condition) }
Encasing the condition in a function will make it evaluate dynamically!
Written by yaojie
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#