Reputation: 5482
I recently made confirmation rule following rails guides like so:
validates :email, email: true, uniqueness: true, confirmation: true
validates :email_confirmation, presence: true
Everything works cool, but when i'm trying to update an existing record, i'm receiving an error:
irb(main):004:0> User.first.update_attributes!(name: "Some Nameee")
User Load (2.9ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]]
(0.4ms) begin transaction
User Exists (0.8ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? AND ("users"."id" != ?) LIMIT ? [["email", "[email protected]"], ["id", 1], ["LIMIT", 1]]
(0.3ms) rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Email confirmation can't be blank
from (irb):4
And it's pretty obvious, because i have presence: true
on :email_confirmation
field. If i'll remove it, you can skip that fild and just don't pass it.
So, what should i do? Just remove :presence
validation?
Upvotes: 1
Views: 114
Reputation: 1492
Why not a conditional validation that checks if email has changed? http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless
validates :email_confirmation, presence: true, if: :email_changed?
Here's the doc on checking if the model instance has changed: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
Upvotes: 4
Reputation: 5482
I've solve it by explicitly defining :on => :create
on validation rule
validates :email_confirmation, presence: true, :on => :create
Is it ok to use it like that? I'm asking, because http://guides.rubyonrails.org/ is not mentioning that, so potentially it can be a bad decision.
Upvotes: 0