views:

38

answers:

1

Hi all, 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...?

+1  A: 

Using a lambda function may work:

validates_length_of :reference, :minimum => lambda{parent.min_length},
                                :maximum => lambda{parent.max_length}
Mark Thomas
well, basically you could specify only min_length (and not max_length) so you should not validate maximum length, and viceversa...
jordinl