2

我一直在为这个问题烦恼一段时间。我有这样的组成员身份:

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships
end

class Membership < ActiveRecord::Base
  attr_accessible :is_owner
  belongs_to :user
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
  has_many :locations
end

组也有许多位置,如下所示:

class Location < ActiveRecord::Base
  belongs_to :group
end

我正在尝试创建一种功能,允许用户仅查看属于其组的位置(组所有权通过成员身份上的 is_owner 字段完成)。这是我一直在尝试的:

can :read, Location, :group => { :memberships => { :user_id => user.id, :is_owner => true } }

这给了我以下错误:

SQLite3::SQLException: no such column: group.memberships

有没有办法创造这种能力?我已经尝试了很多关于这种能力的变化,但都没有奏效。我不能使用块,因为我希望它能够执行索引操作。作为一种变通方法,我正在遍历所有位置并select!用来挑选那些我can :read......显然这不太理想。

4

1 回答 1

0

尝试直接使用 AR:Relation。我没有提到 cancan 如何接受 SQL 连接。

can :read, Location, Location.includes(:group => {:memberships = {}}).where(:group => { :memberships => { :user_id => user.id, :is_owner => true } })

或者:

can :read, Location, Location.includes(:group => {:memberships = {}}).where(["memberships.user_id = ? AND memberships.is_owner is ?", user.id, true]) do |location|
  location.group.memberships.exists?(:user_id => user.id, :is_owner => true)
end
于 2012-12-12T23:50:48.633 回答