4

我们可以根据父对象的关联来检查子对象的权限吗?

Group我在(父级)和之间User通过(关联)有一个多对多关联(参见下面Membership的关联)。我有一个Event属于 aGroup和 a的(子)模型UserMembership有一个名为 的列role,这就是我想要建立权限的基础。

我想确保 auser只能创建 aevent如果它user是属于ownergroup那个eventowner我的意思是有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

知道怎么做吗?

4

1 回答 1

2

听起来您的许可应该基于组:

can :create_events, Group, owner_id: user.id

您是否为组和事件使用嵌套路由?

编辑:

can :create_events, Group, owner: { id: user.id }
于 2012-10-14T18:53:37.223 回答