我正在尝试将 Rails 嵌套资源与 cancan 一起使用。我有一个Dog
模型和一个Friendship
模型。
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
拥有自己的友谊或朋友的友谊。
这是为什么?