Rails - 验证关联的存在? [英] Rails - Validate Presence Of Association?

查看:27
本文介绍了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?

推荐答案

您可以使用 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

或者只是validateshttp://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 => 一起使用,它会存在一个错误.true:嵌套模型和父验证.在本主题中,您可以找到解决方案.

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 - 验证关联的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆