Last Updated: February 25, 2016
·
768
· causztic

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!