我正在嘗試與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
他自己的友誼或他的朋友的友誼。
這是爲什麼?
你可以顯示你的'能力'代碼嗎? – gmaliar 2013-04-22 07:41:05
查看https://github.com/ryanb/cancan/issues/209#issuecomment-609043 – gmaliar 2013-04-22 08:06:05