Having a model1 with belongs_to :model2 association. model2 has an attribute called duration with an integer. model1 has an attribute called start_day. In this model, I want to validate that start_day is less than or equal to duration of model2.开发者_运维技巧
I added the following line to model1:
validates_numericality_of :start_day, :less_than_or_equal_to => :model2.duration
Rails fires a NoMethodError (undefined method `duration' for :model2:Symbol)
model2 has an attribute duration...
Any idea what I am missing? Thanks in advance...
The less_than_or_equal_to
option needs a numerical value, a symbol that names an instance method, or a Proc to be executed at validation time. You probably want the third option:
validates_numericality_of :start_day,
:less_than_or_equal_to => Proc.new { |model1| model1.model2.duration }
Or if you have a method in model1 called model2_duration
you could shorten it to this:
validates_numericality_of :start_day, :less_than_or_equal_to => :model2_duration
精彩评论