About overriding Devise or Clearance controllers
-
21-03-2021 - |
Question
Since authentication gems such as Devise or Clearance uses their own built in controllers, I have a few questions when overriding them. Everytime I've tried to override it, something seems to go wrong and I don't know what it is exactly that caused the error.
For example, to create a new user controller with Devise I understand I have to create a controller like this:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
All good. Now let's say I want to add certain things to the def new
parts of the controller.
1.) To leave the def create
part of the controller alone, I have to put in
def create
super
end
Is that right? Or do I even need to reference it in the new controller at all?
2.) If I type
def new
#my custom code here
end
Does that replace the def new
part of the original Devise controller, or does it just add to it? Meaning to say, do I also have to put in
resource = build_resource({})
respond_with_navigational(resource){ render_with_scope :new }
which is the default behavior for the def new part of the Devise registrations_controller.rb?
3.) There's a filter in Devise that prevents you from signing up if you're logged in, but I need to override this. How do I do this? I'm guessing it has something to do with the prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
part of registrations_controller.rb, but I'm not too sure.
The same questions apply to Clearance, although with slightly different routes and files.. (I'm asking for Clearance too because I haven't decided which authentication gem to use yet -- Clearance appeals to me because of the lightweight code, but Devise has additional features that I would need too).
Solution
1) That's correct.
2) If you want to call the parent's logic, you can call super
at the appropriate point in your sub-class logic.
3) If you override the RegistrationsController, you can call skip_before_filter :require_no_authentication
. This should skip it entirely, so if you need the before filter in certain conditions, you would have to add another before_filter.