Here is the scope that causes code smell:
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? }
Here's what I've tried, but it causes my tests to fail saying the email fields have already been taken:
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
You could group the two lines using with_options
:
Example:
with_options uniqueness: { scope: :client_id }, if: Proc.new { |u| u.active? && u.email } do
validates :email
validates :companyemail
end
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments