1
votes

I've subclassed the devise RegistrationsController for creating new users and added some logic before calling the superclass's 'create' method. So, something like:

class RegistrationsController < Devise::RegistrationsController

def create

super end

I can tell if the superclass encountered an error by checking resource.errors.nil?. However, I want to distinguish between different errors. For instance, I want to do something different if the error is "Email has already been taken" versus some other error return.

I can parse the string, but that seems fragile to me. What if some future upgrade of ActiveRecord or Devise changes the string? What if the string get's localized in some way I don't expect?

Is anyone handling error processing in devise more gracefully than string parsing?

3

3 Answers

0
votes

you can modify devise.en.yml for any default errors

0
votes

Notice that the devise_error_messages helper is just running through the errors attached to whatever you have assigned as your resource object (whatever user model you ran the install generator on).

Now, instead of just printing out the error messages in the helper, you could access their keys in a controller method, as well:

 # in RegistrationsController
 def create
   build_resource
   unless resource.valid?
     if resource.errors.has_key?(:my_error_key)
       # do something
     end
   end
 end

This is just an example, of course, but hopefully it illustrates the approach you might take.

0
votes

With Rails validation errors the devil is in the @details.

A typical validation error on presence looks like this:

> @user.errors
#<ActiveModel::Errors:0x007fe7e8f01234 @base=#<User id: nil, 
email: "[email protected]", created_at: nil, updated_at: nil>,
@messages={:password=>["can't be blank"], :email=>[]},
@details={:password=>[{:error=>:blank}]}>

As you see, the failed validation is accurately described in @details of the ActiveModel Error object.

There is even a short hand method in Rails that makes it easy to test for specific validation errors:

@user.errors.added? :password, :blank

If the password is left blank, this will return true.

More about added? in the Ruby on Rails API: http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-added-3F