Ruby on rails 使用designe和cancan的嵌套资源授权
如何正确授权嵌套了Desive和cancan的资源?我已经执行了文件中建议的程序,但没有成功 这个问题涉及到使用Desive和cancan gems无法从嵌套资源的第三层获取用户id的能力模型。但是,我可以从第二层获取用户id。非常感谢您的帮助 我有一个嵌套资源,如下所示:Ruby on rails 使用designe和cancan的嵌套资源授权,ruby-on-rails,ruby,devise,ruby-on-rails-3.2,cancan,Ruby On Rails,Ruby,Devise,Ruby On Rails 3.2,Cancan,如何正确授权嵌套了Desive和cancan的资源?我已经执行了文件中建议的程序,但没有成功 这个问题涉及到使用Desive和cancan gems无法从嵌套资源的第三层获取用户id的能力模型。但是,我可以从第二层获取用户id。非常感谢您的帮助 我有一个嵌套资源,如下所示: resources :users do resources :clients do resources :positions end end resources :clients d
resources :users do
resources :clients do
resources :positions
end
end
resources :clients do
resources :positions
end
resources :users do
resources :positions
end
resources :users
resources :clients
resources :positions
使用位置
模型控制器,使用以下各项:
class PositionsController < ApplicationController
before_filter :grab_client_from_client_id
load_and_authorize_resource :user
load_and_authorize_resource :client, through: :user, shallow: true
load_and_authorize_resource :position, through: :client, except: [:index], shallow: true
...
end
这会导致非管理员/非管理用户收到以下错误:
用于#的未定义方法“user_id”
显然有些东西设置不正确。我已经一次又一次地浏览了每个gem的文档,并且到处寻找解决方案
我还将在下面提供我的模型关系
class用户
问题在于这一行:
can :read, :all, user_id: user.id
当你检查一个用户是否可以阅读某些内容时,它会检查你试图阅读的内容
由于控制器中有这一行:
load_and_authorize_resource :user
您试图授权的资源是用户
您的能力将比较user.id
和当前用户.id
。用户没有用户id
,因此这就是错误的来源
基于您的代码,我怀疑您希望用户只能阅读属于他的内容,除非他是经理或管理员
您可以通过以下方式实现这一点:
if user.has_role? :admin
can :manage, :all
elsif user.has_role? :management
can [:create, :read, :update], :all
else
can :read, User, id: user.id
can :read, Client, user_id: client.id
can :read, Position, client: { user_id: user.id }
end
这样,用户只能访问与其有关联的模型。问题在于这一行:
can :read, :all, user_id: user.id
当你检查一个用户是否可以阅读某些内容时,它会检查你试图阅读的内容
由于控制器中有这一行:
load_and_authorize_resource :user
您试图授权的资源是用户
您的能力将比较user.id
和当前用户.id
。用户没有用户id
,因此这就是错误的来源
基于您的代码,我怀疑您希望用户只能阅读属于他的内容,除非他是经理或管理员
您可以通过以下方式实现这一点:
if user.has_role? :admin
can :manage, :all
elsif user.has_role? :management
can [:create, :read, :update], :all
else
can :read, User, id: user.id
can :read, Client, user_id: client.id
can :read, Position, client: { user_id: user.id }
end
这样,用户只能访问与其有关联的模型。谢谢!这就是我要找的。谢谢!这就是我要找的。