如果条件为真,我正试图跳过belongs_to关联的验证。 以下是我的代码
class Venue < ActiveRecord::Base has_many :events validates_presence_of :name, :postcode, :category end class Event < ActiveRecord::Base belongs_to :venue accepts_nested_attributes_for :venue end所以我需要做的是,如果Events模型中的条件为真,则跳过Venues validates_presence_of验证。 因此,假设event_type等于'1',则它将忽略Venues validates_presence_of调用,但如果event_type为'2',则它仍将执行validates_presence_of调用。
I'm trying to skip validations of a belongs_to association if a criteria is true. Below is my code
class Venue < ActiveRecord::Base has_many :events validates_presence_of :name, :postcode, :category end class Event < ActiveRecord::Base belongs_to :venue accepts_nested_attributes_for :venue endSo what I need to do is skip the Venues validates_presence_of validation if a criteria from the Events model is true. So lets say if the event_type was equal to '1' then it will ignore the Venues validates_presence_of call but if event_type was '2' then it will still execute the validates_presence_of call.
最满意答案
这个主题有一个Railscast 。 您还可以查看Rails Conditional Validation
根据上面的链接,你必须传递一个lambda,如:
:if => lambda { |venue| venue.event.try(:event_type) == 2 }In the end I did something very similar to this
更多推荐
发布评论