简体   繁体   English

Rails - 验证关联的存在?

[英]Rails - Validate Presence Of Association?

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

You can use validates_presence_of http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_of 您可以使用validates_presence_of http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_of

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

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

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

But there is a bug with it if you will use accepts_nested_attributes_for with :allow_destroy => true : Nested models and parent validation . 但是,有一个与它的错误,如果你会使用accepts_nested_attributes_for:allow_destroy => true嵌套模型和家长确认 In this topic you can find solution. 在本主题中,您可以找到解决方案。

-------- Rails 4 ------------ -------- Rails 4 ------------

Simple validates presence worked for me 简单validates presence对我有用

class Profile < ActiveRecord::Base
  belongs_to :user

  validates :user, presence: true
end

class User < ActiveRecord::Base
  has_one :profile
end

This way, Profile.create will now fail. 这样, Profile.create现在将失败。 I have to use user.create_profile or associate a user before saving a profile . 在保存profile之前,我必须使用user.create_profile或关联用户。

You can validate associations with validates_existence_of (which is a plugin): 您可以使用validates_existence_of (这是一个插件)验证关联:

Example snippet from 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

Alternatively, you can use validates_associated . 或者,您可以使用validates_associated As Faisal notes in the comments below the answer, validates_associated checks if the associated object is valid by running the associated class validations. 正如Faisal下面的评论指出的那样, validates_associated通过运行相关的类验证来检查相关对象是否有效。 It does not check for the presence. 检查存在。 It's also important to note that a nil association is considered valid. 值得注意的是,nil关联被认为是有效的。

If you want to ensure that the association is both present and guaranteed to be valid, you also need to use 如果要确保关联存在且保证有效,则还需要使用

class Transaction < ActiveRecord::Base
  belongs_to :bank

  validates_associated :bank
  validates :bank, presence: true
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM