gdfgdfg gdfgdfg - 1 year ago 171
Ruby Question

Devise, Rails 5, custom errors for email

I have Ajax registration with Rails 5 and Devise. This is

registrations_controller.rb
:

build_resource(sign_up_params)
byebug
if resource.save
if resource.active_for_authentication?
sign_up(resource_name, resource)
return render :json => {:success => true}
else
expire_data_after_sign_in!
return render :json => {:success => true}
end
else
return render :json => {:success => false}
end


With
byebug
when I try to register with email that exist and debug with typing
resource.errors
, I see:

<ActiveModel::Errors:0x00000007254a48 @base=#<User id: nil, email: "[email protected]", role_id: 0, created_at: nil, updated_at: nil>, @messages={:email=>["has already been taken"]}, @details={:email=>[{:error=>:taken, :value=>"[email protected]"}]}>


If I type in the console
resource.errors.messages
, I see this:

{:email=>["has already been taken"]}


I know how to get the message or set for the example:

if resource.errors.details[:email][0][:error] == :taken
return render :json => {:error=> "Email already in use."}
end


or add in the model
user.rb
:

validate :email_uniqueness

def email_uniqueness
self.errors.add(:email, 'Email is already in use') if User.where(:email => self.email).exists?
end


, but I want to change default error message. I searched in the whole project for this message, but found nothing.

How can I change error message in Devise, when email is already in use ?

Answer Source

This is a default Rails validation error message. Read this http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

You can change the message in *.en.yml file like this:

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              taken: is already in use
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download