CanCan -映射控制器到现有的模型



我想"映射" MyControllerUser模型

#ability
class Ability
  include CanCan::Ability
  def initialize user
    user ||= User.new
    if user.has_role? :admin
      can :manage, :all
    else
      can :read, :all
      can :read, User do |u|
        u && u.user_id == user.id
      end
    end
  end
end
#routes
get 'my_controller/show/(:id)', to: 'MyController#show'
#controller
class MyController < ApplicationController
  # load_and_authorize_resource
  def show
    # showing a user
  end
end

所以my_controller/show/(:id)只能被admincurrent user访问。例如,拥有id == 2的用户可以看到自己的配置文件my_controller/show/2,而不能看到其他用户的配置文件,如my_controller/show/1234,除非他们是admin

项目中没有My模型。理想情况下,我必须将MyController重命名为UserController,但由于某种原因,我不允许这样做。

如果我取消load_and_authorize_resourceMyController的注释,将会有一个错误

NameError in MyController#show
uninitialized constant My

那么我怎样才能摆脱它呢?

您可以指定要加载和授权的资源类型的名称:

load_and_authorize_resource :user

否则cancan将尝试按约定(基于控制器的名称)计算。

https://github.com/ryanb/cancan/wiki/authorizing-controller-actions

最新更新