我有一個標準的User
模型,它有一個admin
布爾值。所有的好,好爲有設置爲true的用戶,但對於普通用戶,我得到這個錯誤:Devise的current_user只適用於管理員
undefined local variable or method `current_user'
app/models/doc.rb:18:in `mine'
app/controllers/docs_controller.rb:9:in `index'
上線18 Doc
模型讀取這樣的:
def self.mine
where(:user_id => current_user.name, :retired => "active").order('created_at DESC')
end
我User
模型看起來像這樣:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :current_password
attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :admin
end
class Ability
include CanCan::Ability
def initialize(user)
can :manage, :all if user.admin
end
end
而且在我的應用程序控制器我有以下幾點:
class ApplicationController < ActionController::Base
protect_from_forgery
after_filter :user_activity
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path
end
def admin?
self.admin == true
end
def authenticate_admin
redirect_to :new_user_session_path unless current_user && current_user.admin?
end
private
def user_activity
current_user.try :touch
end
end
我認爲這一切都相關。我不能爲我的生活弄清楚這一點。
我想你需要檢查用戶是否在使用current_user之前登錄。像「如果signed_in?」。 – kengo
它檢查路由的索引方法中的「if user_signed_in?」行。 –