2014-09-05 47 views
0

我試圖用權威人士驗證訪問需要任何數據庫交互的一些靜態的觀點:權威人士:未定義的方法`授權」

class StaticController < ApplicationController 
    include Pundit 
    authorize :splash, :home? 

    def home end 
end 

下面是我的靜態策略。 home?策略總是返回true,所以我應該能夠訪問主視圖。

class StaticPolicy < Struct.new(:user, :static) 
    def initialize(user, resource) 
     @user = user 
     @resource = resource 
    end 

    def home? 
     true 
    end 
end 

相反,我得到這個:

undefined method `authorize' for StaticController:Class 

權威人士完美的作品,如果我授權模式:

def forums_index 
    @forums = Forum.all 
    authorize @forums 
end 

但是,如果我嘗試使用授權法的外部行動,不使用我得到的模型:

undefined method `authorize' for StaticController:Class 

回答

0

那麼,AFAIK你總是要對authorize反對一個對象或類,而CanCan已經「load_and_authorize_resource」,當使用權威人士,你已經知道你必須自己加載和授權的東西(對不起,如果我也是這裏很明顯)。

這就是說,並考慮到您的視圖沒有DB互爲作用,在我看來,對於你的情況下,最好的解決辦法是讓對你的用戶一些自定義的授權,類似

class StaticPolicy < Struct.new(:user, :static) 
    def initialize(user, resource) 
    @user = user 
    @resource = resource 
    end 

    def home? 
    authorize @user, :admin # or suppress the second parameter and let the Policy use the 'home?' method 
    true 
    end 
end 

,並在您UserPolicy

class UserPolicy < ApplicationPolicy 
    def admin # or def home?, it's up to you 
    user.admin? 
    end 
end 

我沒有測試,但是這是主要的想法,這有什麼意義嗎?清楚嗎?

請給它一個嘗試和張貼任何印象,希望它有助於:)