从belongs

编程入门 行业动态 更新时间:2024-10-28 00:15:57
belongs_to关联中跳过validates_presence_of(Skip validates_presence_of from a belongs_to association)

如果条件为真,我正试图跳过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 end

So 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

更多推荐

本文发布于:2023-08-03 02:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1383135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:belongs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!