Devise Error Messages

When it comes to presenting error messages with Devise you are provided with a helper that gives you ‘A simple way to show error messages for the current devise resource’. The helper will not be in your project directory but you can see the full code on Github: https://github.com/plataformatec/devise/blob/master/app/helpers/devise_helper.rb.

Devise encourages you to overwrite if you need to customize but for my purposes that was unnecessary. I had added a user_name attribute to my user model and used it instead of email for authentication. The problem came when I needed to present errors to the user if authentication failed. After entering incorrect credentials my app was not delivering me my descriptive error messages.

One article showed me to debug by placing the devise helper’s resource.errors object into my html:

<%= resource.errors.inspect %>

Which gave me this:

#<ActiveModel::Errors:0x007ff183b328c0 @base=#<User id: nil, email: “”, encrypted_password: “”, reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, user_name: nil>, @messages={}>

As you can see my @messages variable was empty, but why? I had incorrectly entered credentials so shouldn’t there be an error? Turns out that ‘Some devise failure messages are set in rails’s flash object’ and according to the devise github, ‘Remember that Devise uses flash messages to let users know if sign in was successful or unsuccessful.’. This is kind of tricky as I was aware of the flash module of Action Dispatch, http://api.rubyonrails.org/classes/ActionDispatch/Flash.html, but I could not seem to separate that concept from the module helper. They are two totally different things and for some reason Devise will set the flash hash for certain messages while others will be set on the resource variable. All of Devise’s flash messages can be found in your app directory at config/environments/locales/devise.en.yml.

The specific message that WAS being set for me: ‘invalid: “Invalid %{authentication_keys} or password.’. This message was being set on an alert key(:alert), a common idiom along with :notice for flash messages. So to show this message upon authentication failure I coded an error message with similar html to the other devise error messages.

<% if flash.alert %>
<div id=”error_explanation”>
<ul>
<li><%= flash.alert %></li>
</ul>
</div>
<% end %>

Now when users do not enter a correct email or password or both they will receive this generic error message.