在ApplicationController中设计current_user = nil

时间:2014-10-06 02:11:50

标签: ruby-on-rails devise

以下是完整错误:

Can't verify CSRF token authenticity
  User Load (0.3ms)  SELECT  `users`.* FROM `users`  WHERE `users`.`id` = 5  ORDER BY `users`.`id` ASC LIMIT 1
   (0.1ms)  BEGIN
   (0.2ms)  COMMIT
Completed 500 Internal Server Error in 22ms

NoMethodError - undefined method `has_role?' for nil:NilClass:
  app/controllers/application_controller.rb:8:in `authenticate_admin_user!'

我可以通过管理员用户验证我当时是否已登录。

这是触发错误的控制器:

class ApplicationController < ActionController::Base
  def authenticate_admin_user!
    unless current_user.has_role? :admin
      flash[:alert] = "This area is restricted to administrators only."
      redirect_to main_app.root_path 
    end
  end

2 个答案:

答案 0 :(得分:1)

在应用程序控制器中添加此行,以便定义current_user方法

before_action :authenticate_user!

答案 1 :(得分:0)

更改
unless current_user.has_role? :admin

对此:
unless current_user.try(:has_role?, :admin)

它做了什么?try调用:has_role?方法(使用:admin参数,但不是提出异常而是返回{{1} }}