基于datetime属性的存在而不是值的唯一验证?

时间:2018-05-18 16:06:39

标签: ruby-on-rails activerecord

我希望根据是否存在其他日期时间属性,字段是唯一的。

类似的东西:

validates :promo_code, uniqueness: { scope: [:archived_at] }

PASS:

promo_code = TENOFF, archived_at = null

promo_code = TENOFF, archived_at = not null

promo_code = TENOFF, archived_at = not null

FAIL:

promo_code = TENOFF, archived_at = null

promo_code = TENOFF, archived_at = null

通过自定义验证器实现此目的的唯一方法是什么?

2 个答案:

答案 0 :(得分:2)

试试这个,使用if or unless

validates :promo_code, uniqueness: { scope: [:archived_at] }, unless: Proc.new { |o| o.archived_at.blank? }

答案 1 :(得分:0)

这就是我正在做的事情

  validate :unique_code, if: :code

  private

  def unique_code
    return if archived_at.present?
    if self.class.unarchived.where.not(id: id).exists?(code: code, company: company)
      errors.add :code, :invalid
      false
    end
  end