访问在rails控制器中设计current_user变量 [英] Access devise current_user variable in rails controller

查看:136
本文介绍了访问在rails控制器中设计current_user变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Rails(4.0)运行Devise宝石(3.1.0)使用模型用户。我有控制器名为 CollectionsController ,并且我想使用此控制器中的Devise的访问器方法 current_user 获取当前登录的用户对象。

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.

之后,它为CollectionsController返回未定义的局部变量或方法'current_user':Class 。最有趣的是,当我试图在另一个控制器中执行相同操作时,例如 PagesController - 一切正常!

UPD:共享我的控制器的代码:)

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

源代码 current_user 方法由Devise定义,而不是我定义。所以我不认为是这个问题。

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

推荐答案

current_user 是由Devise提供给 ApplicationController 的便利方法。您的控制器应该从它继承:

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

class CollectionsController < ApplicationController

似乎你可能会混淆 ActiveRecord :: Base (由模型子类)与 ActionController (由控制器子类化)。根据 Rails文档

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


默认情况下,只有Rails应用程序中的ApplicationController从ActionController :: Base继承。所有其他控制器依次继承自ApplicationController。

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

这篇关于访问在rails控制器中设计current_user变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆