【问题标题】:Defining a CanCan ability that goes through a belongs_to and a has_many relationship定义通过 belongs_to 和 has_many 关系的 CanCan 能力
【发布时间】:2012-12-12 23:45:23
【问题描述】:

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

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 =&gt; { :memberships =&gt; { :user_id =&gt; user.id, :is_owner =&gt; true } }

这给了我以下错误:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 cancan


    【解决方案1】:

    尝试直接使用 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
    

    【讨论】:

    • 这会抛出Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL,即使没有为:read Location定义其他能力
    • 显示您对位置的所有能力定义。 :read、:index、:show 或任何其他别名为 :read 方法的某处能力设置为哈希。
    • 没有。这是Location的唯一能力。我认为如果没有猴子补丁,我想做的事情是不可能的:github.com/ryanb/cancan/issues/646
    • 好的,我刚刚看了`github.com/ryanb/cancan/blob/master/lib/cancan/model_adapters/…'。您可以尝试将条件作为数组传递。已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    相关资源
    最近更新 更多