2013-04-22 146 views
1

我正在嘗試與cancan一起使用Rails嵌套資源。我有一個Dog模型和一個Friendship模型。與Cancan一起使用嵌套資源

class Dog < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships 
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
    has_many :inverse_friends, :through => :inverse_friendships, :source => :dog  
end 

class Friendship < ActiveRecord::Base 
    belongs_to :dog 
    belongs_to :friend, :class_name => "Dog" 
end 

裏面FriendshipsController我有以下定義:

load_and_authorize_resource :dog 
load_and_authorize_resource :friendship, :through => :dog 

在能力,一個可以:read Dog如果是相同的狗,或者,如果他們是朋友,或者如果這是管理的狗...

 can [:read, :show], Dog do |d| 
      d.id == dog.id or d.friend_of? dog.id 
     end 

一些更多的能力類:

class Ability 
    include CanCan::Ability 

    def initialize(dog) 
    if dog.admin? 
     can :manage, :all 
    else 
     if dog.guest? 
      # anyone can register 
      can [:create], :dog 
     else 
      can [:show, :update, ...], Dog, :id => dog.id 

      can [:read, :show], Dog do |d| 
       ((d.id == dog.id) or (dog.friend_of? d)) 
      end 
     end 

    end 

    end 
end 

管理員可以:index每隻狗的友誼,但狗不能:index他自己的友誼或他的朋友的友誼。

這是爲什麼?

+1

你可以顯示你的'能力'代碼嗎? – gmaliar 2013-04-22 07:41:05

+1

查看https://github.com/ryanb/cancan/issues/209#issuecomment-609043 – gmaliar 2013-04-22 08:06:05

回答

0

您已爲管理員授予「管理」「所有」權限,因此他可以看到所有的友誼。

但是你沒有給予任何非管理員友誼的權限。

跳過索引操作的「友誼」授權。

load_and_authorize_resource :friendship, :through => :dog, :except => [:index] 

在友誼控制器中,索引動作將根據狗模型進行授權,所有其他動作將基於狗以及友誼模型進行授權。

+0

謝謝!我會在即將到來的日子裏嘗試。 – 2013-05-19 10:16:49