2013-01-09 73 views
0

我有一個標準的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 

我認爲這一切都相關。我不能爲我的生活弄清楚這一點。

+0

我想你需要檢查用戶是否在使用current_user之前登錄。像「如果signed_in?」。 – kengo

+0

它檢查路由的索引方法中的「if user_signed_in?」行。 –

回答

1

current_user幫助程序是一種無法從模型訪問的控制器方法。您應該將當前用戶作爲參數從控制器傳遞給模型。

def self.mine(current_user) 
    where(:user_id => current_user.name, :retired => "active").order('created_at DESC') 
end 

編輯:附註

看起來user_id是你的邏輯的字符串。如果這是你正在做的事情,你應該重新考慮。通過使用數據庫中的標識符來設置一個belongs_to和has_many是更加可維護的。使用字符串ID是非常規的,它是一個兔子洞,在非常糟糕的地方結束。

+0

這很棒!乾杯。你是否碰巧知道類似的命名範圍中的某種語法的語法,這種命名範圍生活在一個模型中,即scope:tagged_articles,lambda {tagged_with([current_user.billing,current_user.shadow],:any => true)? –

+0

並採取關於字符串的一點。這是舊的,但我仍然沒有改變它。 –

+1

'scope:mine,lambda {| current_user |其中(:user_id => current_user.name,:retired =>「active」)。order('created_at DESC')}'應該這樣做 –

相關問題