Rails - 验证关联的存在?
我有一个模型 A,它与另一个模型 B 具有“has_many”关联。我有一个业务要求,即插入 A 需要至少 1 个与 B 相关的记录。是否有我可以调用的方法来确保这是真的,或者我需要编写自定义验证吗?
I have a model A that has a "has_many" association to another model B. I have a business requirement that an insert into A requires at least 1 associated record to B. Is there a method I can call to make sure this is true, or do I need to write a custom validation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
validates_presence_of
http://apidock.com/rails/ ActiveModel/Validations/ClassMethods/validates_presence_of或只是
validates
http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates
但是,如果您将
accepts_nested_attributes_for
与:allow_destroy => 一起使用,则会出现错误。 true
:嵌套模型和父验证。在本主题中您可以找到解决方案。You can use
validates_presence_of
http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_ofor just
validates
http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates
But there is a bug with it if you will use
accepts_nested_attributes_for
with:allow_destroy => true
: Nested models and parent validation. In this topic you can find solution.-------- Rails 4 ------------
简单的
验证
存在
对我有用这样,
Profile。 create
现在将失败。在保存个人资料
之前,我必须使用user.create_profile
或关联用户。-------- Rails 4 ------------
Simple
validates
presence
worked for meThis way,
Profile.create
will now fail. I have to useuser.create_profile
or associate a user before saving aprofile
.如果要确保关联既存在又保证有效,还需要使用
If you want to ensure that the association is both present and guaranteed to be valid, you also need to use
您可以验证与
validates_existence_of
(这是一个插件)的关联:示例片段来自此博客条目:
或者,您可以使用
validates_linked
。正如 Faisal 在答案下方的评论中指出的 ,validates_linked
通过运行关联的类验证来检查关联的对象是否有效。它不检查是否存在。同样重要的是要注意,零关联被认为是有效的。You can validate associations with
validates_existence_of
(which is a plugin):Example snippet from this blog entry:
Alternatively, you can use
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. It does not check for the presence. It's also important to note that a nil association is considered valid.