0

我有使用设备和 cancancan 的用户模型。这是我的能力:

if user.role? :patient
         can :access_profile, User, :id => user.id
end

其中 access_profile 别名是:

alias_action :show, :edit, :update, :destroy, :to => :access_profile

在我的 users_controller 中,我使用 load_and_authorize_resource。例如,当我尝试“users/4”和 current_user.id = 3 时,我能够到达那里。

在日志中我看到这个:

User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 4]]
User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 3]]
  Rendered users/show.html.erb within layouts/application (0.4ms)

这里第一个查询来自 set_user 方法。我猜第二个查询会加载我的资源以进行授权。在这里,由于 current_user.id = 3 并且在第二个查询中我也看到了 3,我想这就是我被授权的原因。但我猜,第二个查询中的 id 必须是 4。

怎么做才能使 load_and_authorize 方法正常工作。

4

1 回答 1

0

您确定自动加载实例有效吗?如果实例无法加载,Cancancan 将使用 Class 作为对象来检查能力,如果定义了对 Class 的访问将始终返回 true(无论参数如:id

将 load_and_authorize_resource 更改为 load_resource 并检查是否authorize! :access_profile, @user在 access_profile 操作中使用也会保护访问。

您也可以直接在实例上定义能力: can :access_profile, user而不是在用户类上定义。

于 2015-08-29T12:25:44.350 回答