Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 335
Dima Knivets Avatar asked Oct 02 '13 22:10

Dima Knivets


3 Answers

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.

like image 171
zeantsoi Avatar answered Nov 07 '22 13:11

zeantsoi


Add before_action :authenticate_user! to your controller.

see: https://github.com/plataformatec/devise#controller-filters-and-helpers

like image 39
Yuki Matsukura Avatar answered Nov 07 '22 15:11

Yuki Matsukura


I was having the same problem. Some controllers could access current_user and others could not. In one case, it was an erb file that was accessing current_user but only after asking user_signed_in? I added that check in my controller code and voila! current_user was available.

like image 42
user3468739 Avatar answered Nov 07 '22 14:11

user3468739