[英]Rails: Validate attribute presence for at least one record in each group
I am trying to do something like: 我正在尝试做类似的事情:
validates :primary_product, presence: { scope: :student_id }
There can be multiple rows with same student_id
. 可以有多个具有相同
student_id
行。 For set of all rows(with same student_id
) at least one value of primary_product
should be present. 对于所有行集(具有相同的
student_id
),至少应存在primary_product
值。 This does not seem to work. 这似乎不起作用。 Not sure if I can apply scope with presence.
不知道我是否可以在现场应用范围。
You can try the following, using custom validation: 您可以使用自定义验证尝试以下操作:
validates :primary_product, if: -> x {
where.not(primary_product: nil).exists?(student_id: x.student_id)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.