2011-09-05 68 views
1

真的很困惑。角色建立並且在one role per user method之後很好地工作。我的用戶模式如下。每個用戶一個角色CanCan,未定義的方法「角色」問題

class User < ActiveRecord::Base 

    ROLES = %w[admin landlord] 

    def role?(role) 
    roles.include? role.to_s 
    end 
end 

這是當我將權限添加到我的能力模型我得到以下錯誤。

undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x10433a5e0> 

我的能力模型如下。

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    if user.role == "admin" 
     can :manage, :all 
    else 
    can :read, :all 
    end 
    end 
end 

這裏是我在終端中看到的。

NoMethodError (undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x1044d46a8>): 
    app/models/ability.rb:5:in `initialize' 
    app/controllers/application_controller.rb:6:in `new' 
    app/controllers/application_controller.rb:6:in `current_ability' 

正如你可以告訴我只是學習!即使向正確的方向推動也會令人驚歎。謝謝。

+0

我猜有一個與CURRENT_USER值的問題。你在使用設計嗎?你在current_ability中定義了什麼? – e3matheus

+0

我沒有使用Devise,只是編寫了我擁有的Rails 3書籍的登錄名。 def current_ability @ current_ability || = Ability.new(session) end – Delete

回答

1

的問題是,你定義role?方法,但在ability.rb調用role方法這當然是未定義

正確的方式做的,將被

def initialize(user) 
    if user.role? "admin" 
    can :manage, :all 
    else 
    can :read, :all 
    end 
end 
0

您傳遞一個會話可以可以。您需要傳遞當前登錄的用戶。我在對rails書籍的解釋中猜測,應該有辦法從變量會話中訪問該用戶。將該用戶作爲參數傳遞給該能力。

如果用戶沒有登錄,我會發送一個新的用戶。

您將需要重構的代碼,類似:

def current_ability 
    if session[:user_id] # Replace with the method to get the user from your session 
    user = User.find(session[:user_id]) 
    else 
    user = User.new 
    end 

    @current_ability ||= Ability.new(user) 
end 
+0

我明白了,感謝您的參與。那麼我編輯我的代碼說。 高清current_ability @current_ability || = Ability.new(會話[:USER_ID]) 結束 但這個錯誤我現在得到的是: 未定義的方法'的角色「? for 3:Fixnum – Delete

+0

您正在傳遞用戶的ID,但不是用戶本身。如果session [:user_id]存在,你需要找到用戶(就像我在代碼中發佈的那樣) – e3matheus

相關問題