我们可以根据父对象的关联检查子对象的权限吗?
我在Group
(父级)和User
之间,通过Membership
(关联)之间存在多对多关联(请参阅下面的关联)。我有Event
(孩子)模型,属于Group
和User
。 Membership
有一个名为role
的列,这就是我想要的权限。
如果user
是event
的{{1}} user
,我希望确保owner
只能创建group
event
} 属于。 owner
我的意思是Membership.where(user_id: user, group_id: group, role: 'admin')
记录。
文档在Accessing Parent in Ability下提到了这一点,但他们没有提及通过关联。
# in Ability
can :manage, Task, :project => { :user_id => user.id }
将该示例翻译成我的用例:
# in Ability
can :create, Event, :group => { group.owner == user }
我已经有一个group.owner设置:
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group, inverse_of: :memberships
end
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
has_many :ownerships, class_name: 'Membership', conditions: { role: 'admin' }
has_many :owned_groups, through: :ownerships, source: :group
has_many :events
end
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
has_one :ownership, class_name: 'Membership', conditions: { role: 'admin' }
has_one :owner, through: :ownership, source: :user
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :organizer, class_name: 'User', foreign_key: 'user_id'
belongs_to :group
end
知道怎么做吗?
答案 0 :(得分:2)
听起来你的许可应该以集团为基础:
can :create_events, Group, owner_id: user.id
您是否正在为群组使用嵌套路由&amp;事件
修改强>
can :create_events, Group, owner: { id: user.id }