Reputation: 2467
:inclusion => {:in => r = (1..15), :min => r.first, :max => r.last}
This is working code I have. The thing I wanted to make dynamic is the "15" part, e.g
:inclusion => {:in => r = (1..Vehicle.max_passengers), :min => r.first, :max => r.last}
I have defined the following class method:
def self.max_passengers
15
end
Of course it didn't work. I've tried using Procs and lambdas, but It didn't work properly for me. :( Can someone help me with this one - is it possible ?
Upvotes: 0
Views: 3055
Reputation: 1872
You're looking for a custom validation method:
ActiveRecord::Base.class_eval do
def self.validates_max_passenger(attr_name, r)
validates attr_name, :inclusion => { :in => r, :min => r.first, :max => r.last } }
end
end
# later in your class of choice:
validates_max_passenger :passengers, 1..5
Or, you can try the following with lambda
def self.max_passengers
1..15
end
validates :attrib, :inclusion => {:in => lambda { |obj| ClassName.max_passengers } }
Note that you won't need the min/max if you're using :in
on range.
Upvotes: 3
Reputation: 1590
Check if validates_with
is of any help.This helper passes the record to a separate class for validation in which you can make your validation criteria dynamic i.e by reading some config or so on.
More info on validates_with
is available at ruby on rails guide
class Person < ActiveRecord::Base
validates_with GoodnessValidator
end
class GoodnessValidator < ActiveModel::Validator
def validate(record)
# implement your dynamic criteria here
end
end
Upvotes: 0