jordinl
jordinl

Reputation: 5239

dynamic validates_length_of

I' trying to do a validates_length_of, but specifying the range/minimum/maximum at run time.

For instance, we have a parent model:

class Parent < ActiveRecord::Base
  has_many :children

  # with attributes min_length, max_length
end

And a child model:

class Child < ActiveRecord::Base
  belongs_to :parent

  # with an attribute reference
end

So what I'd like to do in the Child class is:

validate :reference_length

def reference_length
  options = { :within => parent.min_length..parent.max_length }
  self.class.validates_length_of :reference, options
end

But it doesn't work, is there a way to do that without doing errors.add(:reference, message) if...?

Upvotes: 1

Views: 687

Answers (1)

Mark Thomas
Mark Thomas

Reputation: 37517

Using a lambda function may work:

validates_length_of :reference, :minimum => lambda{parent.min_length},
                                :maximum => lambda{parent.max_length}

Upvotes: 2

Related Questions