2011-04-16 76 views
89

我有一个与另一个模型B有“has_many”关联的模型A.我有一个业务需求,插入到A需要至少1个关联的记录到B.是否有一个方法,我可以调用以确保这是真的,还是我需要编写自定义验证?Rails - 验证存在的关联?

回答

140

您可以使用validates_presence_ofhttp://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_of

class A < ActiveRecord::Base 
    has_many :bs 
    validates_presence_of :bs 
end 

或只是validates http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates

class A < ActiveRecord::Base 
    has_many :bs 
    validates :bs, :presence => true 
end 

但是有它的错误,如果你会使用accepts_nested_attributes_for:allow_destroy => trueNested models and parent validation。在这个主题中你可以找到解决方案。

+3

'的has_many:bs' lulz – Archonic 2016-10-28 00:24:37

6

您可以验证关联与validates_existence_of(这是一个插件):

实施例从this blog entry片段:

class Tagging < ActiveRecord::Base 
    belongs_to :tag 
    belongs_to :taggable, :polymorphic => true 
    validates_existence_of :tag, :taggable 

    belongs_to :user 
    validates_existence_of :user, :allow_nil => true 
end 

备选地,可以使用validates_associated。由于Faisal notes in the comments低于答案,validates_associated通过运行关联的类验证来检查关联的对象是否有效。它确实不是检查存在。注意到一个无关联被认为是有效的也很重要。

14

--------轨道4 ------------

简单validatespresence工作对我来说

class Profile < ActiveRecord::Base 
    belongs_to :user 

    validates :user, presence: true 
end 

class User < ActiveRecord::Base 
    has_one :profile 
end 

这样,Profile.create现在将失败。我必须在保存profile之前使用user.create_profile或关联用户。

0

如果你想确保该组织是当前和保证是有效的,你还需要使用

class Transaction < ActiveRecord::Base 
    belongs_to :bank 

    validates_associated :bank 
    validates :bank, presence: true 
end