Search code examples
ruby-on-railsdevise

Access devise current_user variable in rails controller


I've got Rails (4.0) running Devise gem (3.1.0) using model User. I have controller named CollectionsController and I want to get current logged in user object with Devise's accessor method current_user in this controller.

And after that it returns undefined local variable or method 'current_user' for CollectionsController:Class. The most interesting thing is that when I'm trying to do the same in another controller, for example PagesController — everything works perfectly!
UPD: sharing the "code" of my controller :)

class CollectionsController < ActionController::Base
    def index
         @user = current_user
    end
end

the source of current_user method is defined by Devise, not me. So I don't think that is the problem.


Solution

  • current_user is a convenience method made available by Devise to ApplicationController. Your controller should be inheriting from it:

    class CollectionsController < ApplicationController
    

    It seems you may be conflating ActiveRecord::Base (subclassed by models) with ActionController (subclassed by controllers). According to Rails docs:

    By default, only the ApplicationController in a Rails application inherits from ActionController::Base. All other controllers in turn inherit from ApplicationController.