【问题标题】:CanCan(Can) and Activeadmin: Index on nested relationsCanCan(Can) 和 Activeadmin:嵌套关系索引
【发布时间】:2024-12-09 21:45:02
【问题描述】:

我将 CanCan(Can) 与 ActiveAdmin 一起使用。但是,我很难让 CanCan(Can) 在索引上正常工作,以实现“has_many through”关系。

基本上我的 Invoice 模型如下所示

class Invoice < ActiveRecord::Base

  belongs_to :order
  belongs_to :country
  belongs_to :currency

  has_one :user, :through => :order
(…)

我的订单模式是这样的

class Order < ActiveRecord::Base

  belongs_to :user
  belongs_to :product

  has_many :invoices

我的用户模型是这样的

class User < ActiveRecord::Base

  has_many :orders
  has_many :invoices, :through => :orders

我的能力是这样定义的

可以:read, Invoice, :user => adminuser.user

这适用于个别发票。所以正确的用户可以看到这个 URL :3000/admin/invoices/1 而其他用户会得到一个未授权的错误。

但是在索引列表中它完全向南。 :3000/admin/invoices/ 返回错误信息

Mysql2::Error: 'where 子句'中的未知列'invoices.user_id': SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM invoices WHERE invoices.user_id = 2 LIMIT 30 OFFSET 0) subquery_for_count

显然这是完全错误的,因为 CanCan(Can) 正在查看错误的表格。如何设置 ActiveAdmin 和 CanCan(Can) 以使用“通过”查找索引上的这种关系?我已经尝试添加

def authorize_access!
  load_and_authorize_resource :through => :order
end   

到“ActiveAdmin.register Invoice”的控制器,但没有区别。

任何建议将不胜感激!

【问题讨论】:

    标签: ruby-on-rails activeadmin cancan cancancan


    【解决方案1】:

    试试这个:can :read, Invoice, :user =&gt; { :id =&gt; adminuser.user.id }

    【讨论】: