am-rails
am-rails

Reputation: 1473

How to Fix Conditional Validations in Rails Model?

I have the following validation in my User model. I don't want it to run when the user is a guest, so I added an unless proc:

with_options :unless => :guest_user? do |user|
    before_save { |user| user.email = email.downcase }
    validates :email, presence: true, uniqueness: {case_sensitive: false}
end

This calls the method guest_user? and shouldn't run when the user is a guest. However, the validation runs in all cases. How do I fix the unless proc so it works?

Upvotes: 3

Views: 57

Answers (1)

bbozo
bbozo

Reputation: 7311

Try

with_options :unless => :guest_user? do |o|
    o.before_save { |user| user.email = email.downcase }
    o.validates :email, presence: true, uniqueness: {case_sensitive: false}
end

Upvotes: 5

Related Questions