未定义的方法`user_signed_in?' for ApplicationController:Class,Devise

时间:2011-11-29 05:13:04

标签: ruby-on-rails devise

以下代码:

class ApplicationController < ActionController::Base
  protect_from_forgery

  if user_signed_in?
  end
end

产生此错误:

undefined method `user_signed_in?' for ApplicationController:Class, Devise

我查看了这个post,但我不知道他的意思是应用程序控制器的实例与应用程序控制器的定义。我有devise_for:在config / routes.rb文件中设置的用户,我没有使用clear_helpers,并且在我的user.rb文件中有:database_authenticatable。如果if语句在不同控制器中的动作中,则该if语句可以正常工作。为什么不在这里工作?我是否需要以某种方式传递设计助手?

1 个答案:

答案 0 :(得分:2)

他说使用控制器类定义本身调用函数,而不是控制器类的实例。在代码self == ApplicationController中,他将self与类定义ApplicationController的引用进行比较,而不是ApplicationController的特定实例(或对象)。

在这种情况下,帖子基本上是在控制器的方法中调用debugger函数,而不仅仅是控制器定义中的某个位置。

正如帖子提到的,你应该调用user_signed_in?在实例的上下文中,而不是定义。所以把它放在一个用于过滤器之类的方法中。例如:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def find_user_name
     if user_signed_in?
        return user.user_name
     end
  end

end