【问题标题】:Is it possible to use Can? in ActiveAdmin controllers (using cancancan gem)可以用Can吗?在 ActiveAdmin 控制器中(使用 cancancan gem)
【发布时间】:2020-05-12 07:06:07
【问题描述】:

can? 真的在 AA 中工作吗?使用 AA 2.6.1 和 Rails 6 和 Ruby 2.6.5。

我在 latest AA documentation 和许多其他帖子中看到 can? 方法应该可以在 AA 资源控制器中调用,例如

index do
  column :title, sortable: false
  column :secret_data if can? :manage, Post
end

但是,如果我将这样的 if 语句添加到我的 :index 列中,我会得到一个错误。 “未定义的方法‘可以吗?’对于 nil:NilClass"

这是一个简单的上下文,应该适用于初学者,但我想做的事情有点复杂。

我有一个 AdmixUser 模型和一个 Group 模型,以及一个将 AdmixUser 的角色存储在 Group 中的嵌套资源 Grouprelationship。在 Group#show 页面上有一个 table_for 组的关系如下:

table_for resource.grouprelationships do
  column :action_test do |gr|
    para link_to "Edit Relationship", edit_admix_grouprelationship_path(gr.id)
 end
end

在我的Ability.rb:

    can :read, Grouprelationship, group_id: mygroups
    can :update, Grouprelationship do |gr|
      user_role=Grouprelationship.find_by(admix_user_id: user.id, group_id: gr.group_id).role
      return true if user_role==Grouprelationship::PI #PI can do anything
    end

这里的逻辑是,如果我在组中的角色是“PI”,那么我一个人可以更新组中其他人的角色。

就 AA 而言,此逻辑运行正常。如果非 PI 用户跟随表中的link_to,它肯定会执行 Ability 类中的块,并且控制器会闪烁通知该操作未授权。但首先不提供指向未经授权页面的链接会更干净。如果我将link_to 行更改为:

para link_to "Edit Relationship", edit_admix_grouprelationship_path(gr.id) if can? :update, gr

然后它会抛出相同的未定义方法错误。

在 AA 中很难找到最近对 can? 方法的讨论。在旧时代,例如this link,看来有必要用load_and_authorize_resource修改资源的控制器,但我的AA控制器中不存在这种方法。

所以最后的问题是如何配置资源以启用can?,否则我做错了什么?

可能会有些复杂,因为我使用的是自定义用户模型“admix_user”和命名空间“admix”,但我似乎已经正确设置了这个,因为 CanCanCan 授权在每个 AA 上下文中都有效,除了上面使用 can?

【问题讨论】:

    标签: activeadmin ruby-on-rails-6 cancancan


    【解决方案1】:

    阅读AA文档,正确用法不是can?而是authorized?。即在我的控制器中,当我使用

    时表格正确显示
    table_for resource.grouprelationships do
      column :action_test do |gr|
        para link_to "Edit Relationship", edit_admix_grouprelationship_path(gr.id) if authorized? :update, gr
     end
    end
    

    完成这项工作。由于文档相互冲突,我感到困惑:here 使用了 can?here 定义了 authorized?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 2017-11-22
      • 2021-08-09
      • 2017-09-30
      相关资源
      最近更新 更多