两个字段的自定义验证具有相同的验证但略有不同

时间:2014-07-18 19:45:54

标签: ruby-on-rails

以下是导致代码异味的范围:​​

validates :email, uniqueness: { scope: :client_id }, if: Proc.new {|u| u.active? and !u.email.blank? }
validates :companyemail, uniqueness: { scope: :client_id }, if: Proc.new {|u| u.active? and !u.companyemail.blank? }

这是我尝试过的,但它导致我的测试失败,说已经采取了电子邮件字段:

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors[attribute] << 'has already been taken' if record.active? and !attribute.blank?
  end
end

validates :email, :companyemail, uniqueness: { scope: :client_id }, email: true

2 个答案:

答案 0 :(得分:1)

您可以使用with_options对这两行进行分组:

示例:

with_options uniqueness: { scope: :client_id }, if: Proc.new { |u| u.active? && u.email } do 
  validates :email
  validates :companyemail
end

答案 1 :(得分:0)

当我读取您的代码时,每次记录处于活动状态且电子邮件地址存在时,此验证程序都会失败。

您是否看过使用allow_blank: true选项? http://edgeguides.rubyonrails.org/active_record_validations.html#:allow_blank

可能是这样的:

validates :email,: companyemail uniqueness: { scope: :client_id },  if: "record.active?", allow_blank: true