我们可以根据父对象的关联来检查子对象的权限吗?
Group
我在(父级)和之间User
通过(关联)有一个多对多关联(参见下面Membership
的关联)。我有一个Event
属于 aGroup
和 a的(子)模型User
。Membership
有一个名为 的列role
,这就是我想要建立权限的基础。
我想确保 auser
只能创建 aevent
如果它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
知道怎么做吗?