2011-11-22 89 views
3

我有一定的要求,其中視圖根據用戶類型具有不同的內容。可以說我有用戶控制器的索引操作。那麼我可以用康康舞授權這樣使用cancan正確的方式

authorize! :index, @users 

作用進一步用於過濾我有一個像

if can :view_all,User

另一個授權另外像

if can :view_some,User另一個授權將需要另外一個內容。

這會導致很多條件。相反,我可以使用簡單的條件,如

If the user is with view_all access show him all 
else if the user is with view_some access show him some 
else access denied 

康康需要一個額外的查詢,不是嗎?我可能會以錯誤的方式使用康康。所以需要一些建議。

這裏是我的ability.rb文件

can :index, User do |user1| 
     role.accesses.include?(Access.where(:name => "access1").first) || role.accesses.include?(Access.where(:name => "access2").first) 
    end 

    can :view_all, User do |user1| 
     role.accesses.include?(Access.where(:name => "access1").first) 
    end 

    can :view_some, User do |user1| 
     role.accesses.include?(Access.where(:name => "access2").first) 
    end 
+0

你能告訴我們你的ability.rb ? – Dogbert

+2

請標記您已回答的其他問題。 – Petrogad

回答

0

慘慘的粗略片段需要一個額外的查詢?

當組合能力時,cancan將使用單個查詢。

如果你看看規格,例如。 spec/cancan/model_adapters/active_record_adapter_spec.rb,你會發現規格如下:

it "should fetch any articles which are published or secret", focus: true do 
    @ability.can :read, Article, :published => true 
    @ability.can :read, Article, :secret => true 
    article1 = Article.create!(:published => true, :secret => false) 
    article2 = Article.create!(:published => true, :secret => true) 
    article3 = Article.create!(:published => false, :secret => true) 
    article4 = Article.create!(:published => false, :secret => false) 
    Article.accessible_by(@ability).should == [article1, article2, article3] 
end 

如果你打開SQL日誌記錄,您將看到查詢相結合的條件:

Article Load (0.2ms) 
SELECT "with_model_articles_95131".* 
FROM "with_model_articles_95131" 
WHERE (("with_model_articles_95131"."secret" = 't') 
    OR ("with_model_articles_95131"."published" = 't'))