简体   繁体   中英

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... ?

Using a lambda function may work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM