【问题标题】:Rails: Validate attribute presence for at least one record in each groupRails:验证每个组中至少一条记录的属性存在
【发布时间】:2016-06-23 10:21:11
【问题描述】:

我正在尝试做类似的事情:

validates :primary_product, presence: { scope: :student_id }

可以有多个具有相同student_id 的行。对于所有行的集合(具有相同的student_id),至少应该存在一个primary_product 值。这似乎不起作用。不确定我是否可以在存在时应用范围。

【问题讨论】:

  • validates :primary_product, if: :student_id??如果没有,您能否给出更详细的阐述?
  • 可以有多行具有相同的student_id。对于所有行的集合,至少应该存在一个 primary_product 值。

标签: ruby-on-rails validation activerecord rails-activerecord


【解决方案1】:

您可以使用自定义验证尝试以下操作:

validates :primary_product, if: -> x {
  where.not(primary_product: nil).exists?(student_id: x.student_id)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2014-12-06
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多