【问题标题】:CanCan and ActiveRecord associationsCanCan 和 ActiveRecord 关联
【发布时间】:2014-11-26 18:38:35
【问题描述】:

我的 Ability.rb 中有以下行

can :index, :calls, :store => { area_id: user.area_id }

在calls_controller.rb中

load_and_authorize_resource :store
load_and_authorize_resource :call, :through => :store

def index
    @calls = Call.accessible_by(current_ability, :index)
end

在模型call.rb中

belongs_to :store

然而,当我尝试在视图中访问 @calls 时,出现以下 SQL 错误

Mysql::Error: Unknown column 'store.area_id' in 'where clause': SELECT  `calls`.* FROM `calls` INNER JOIN `stores` ON `stores`.`id` = `calls`.`store_id` WHERE `store`.`area_id` = 4 LIMIT 20 OFFSET 0

这是因为 SQL 查询应该有“WHERE stores.area_id = 4”。这是 CanCan 的问题还是我的设置有问题? 我正在使用 CanCan 2.0,仅供参考。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord cancan cancancan


    【解决方案1】:

    尝试将能力更改为:

    can :index, Call, :store => { area_id: user.area_id }
    

    【讨论】:

    • 有趣。这不会出错,但它允许用户查看所有调用,而不仅仅是区域 4 中的调用。我正在这里构建一个新项目,因此 Ability.rb 或任何可能干扰 afaik 的控制器中几乎没有任何内容。
    • 我确定语法不起作用。比较:can [:read, :index], :calls, :id => 55866 和 can [:read, :index], Call, :id => 55866。后者可以让您查看所有呼叫,前者只是一个
    • 不知道出了什么问题,但你为什么不试试cancancan,因为cancan 支持现在已经放弃了一段时间,这可能是一个老问题!
    【解决方案2】:

    如果您限制用户可以看到的商店

      if !user.area_id.nil? and user.area_id != 0 then
        user_stores = Store.where(:area_id => user.area_id)
      end
    

    然后你可以在条件中传递一个数组

      can [:read, :index], :stores, :id => user_stores
      can [:read, :index, :create, :update], [:calls, :change_requests], :store_id => user_stores
    

    按要求工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多