开发者

Rails - Validate field in another model

Need some help on figuring out how to validate one field if and only if another field in a related model is of a certain value. For example:

//My Models

class Course < ActiveRecord::Base
  has_many :locations, :dependent => :destroy
  accepts_nested_attributes_for :locations
end

class Location < ActiveRecord::Base
  belongs_to  :course
end

A course can have many locations (state, city, etc) as well as a start_date. I want to have something like: "Allow location.start_date to be blank ONLY IF course.format开发者_C百科 == 'DVD'"

In my Location model I tried something like:

validates_presence_of   :start_date,
                        :message => "Start Date can't be blank",
                        :allow_blank => false,
                        :if => Proc.new { |course| self.course.format != 'DVD' }

Then when I use that, I get: private method 'format' called for nil:NilClass

Not sure if I'm on the right track here.

Thanks!


The Proc passed to the if clause passes as a parameter to the block the instance of the current object being validated. So, what you have as |course| is really |location|. Try something like the following and see if it does what you want:

validates_presence_of   :start_date,
                        :message => "Start Date can't be blank",
                        :allow_blank => false,
                        :if => Proc.new { |location| location.course.format != 'DVD' }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜