how to check if email exists from object errors array Rails
I am creating users from emails. If an email exists I want to skip creating that user.
Here is my model method:
def invite_users(emails, board)
invalid_emails =[]
emails.each do |email|
user = User.new(:email => email)
user.save ? Participant.make(user, board) : invalid_emails << email unless user.errors.each {|key, msg| msg == "has already been taken"}
end
invalid_emails if invalid_emails.any?
end
I want to check if the error generated from user.save is a duplicate email error. If so I don't want to put that email in the invalid_ema开发者_如何学编程ils array.
How can I do this?
validates_uniqueness_of is useless for such purposes.
The canonical thing to do is to add a unique index on email to the users table, and use code like:
begin
-- do stuff that creates records --
rescue ActiveRecord::StatementInvalid => e
raise unless /Mysql::Error: Duplicate entry/.match(e)
end
if you want to emulate create or find, you do something like
result = nil
begin
result = User.create(:email => xxxx)
rescue ActiveRecord::StatementInvalid => e
if /Mysql::Error: Duplicate entry/.match(e)
user = User.find_by_email(xxx)
else
raise
end
end
just change
user = User.new(:email => email)
user.save ? Participant.make(user, board) : invalid_emails << email unless user.errors.each {|key, msg| msg == "has already been taken"}
to
user = User.new(:email => email)
if User.find_by_email( email ).blank?
Participant.make(user, board)
else
invalid_emails << email
end
Since errors
is basically an array you could just change each
to any
to get a boolean value for your condition.
精彩评论