如何使用cancan对一系列资源进行授权?
我有一个非静态控制器,我正在尝试使用 cancan 授权!方法来应用权限。
我有一个 delete_multiple 操作,其启动方式如下,
def delete_multiple
@invoices = apparent_user.invoices.find(params[:invoice_ids])
我想在继续之前检查用户是否有权删除所有这些发票。如果我使用
authorize! :delete_multiple, @invoices
许可被拒绝。我的ability.rb 包括以下内容
if user.admin?
can :manage, :all
elsif user.approved_user?
can [:read, :update, :destroy, :delete_multiple], Invoice, :user_id => user.id
end
这是循环遍历我的数组并单独调用授权的问题还是有更智能的处理方法?我开始觉得手动授权比使用 cancan 来处理复杂的非静态控制器更容易(尽管我的应用程序中有很多其他静态控制器,效果很好)。
I have a non-restful controller that I am trying to use the cancan authorize! method to apply permissions to.
I have a delete_multiple action that starts like so
def delete_multiple
@invoices = apparent_user.invoices.find(params[:invoice_ids])
I want to check that the user has permission to delete all of these invoices before proceeding. If I use
authorize! :delete_multiple, @invoices
permission is refused. My ability.rb includes the following
if user.admin?
can :manage, :all
elsif user.approved_user?
can [:read, :update, :destroy, :delete_multiple], Invoice, :user_id => user.id
end
Is it a matter of looping through my array and calling authorize individually or is there a smarter way of doing things? I'm starting to feel like doing authorizations would be easier manually than by using cancan for a complicated non-restful controller (although I have plenty of other restful controllers in my app where it works great).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有点晚了,但你可以在你的能力类中写这个
编辑
这也可以写成:
A little late in here but you can write this in your ability class
EDIT
This can be written also as:
似乎
authorize!
仅适用于单个实例,不适用于数组。以下是我使用 Rails 3.2.3 和 CanCan 1.6.7 解决这个问题的方法。基本思想是计算用户尝试删除的总记录数,计算
accessible_by (current_ability, :destroy)
的记录数,然后比较计数。如果您只想要一个用户有权销毁的记录数组,则可以使用
accessible_by (current_ability, :destroy)
返回的数组。不过,我使用的是destroy_all
,它直接作用于模型,所以我最终得到了这个计数和比较解决方案。值得检查开发日志以查看两个
SELECT COUNT
语句的外观:第二个语句应为 CanCan 施加的授权限制添加WHERE
短语。我的示例涉及删除多条消息。
能力.rb
messages_controller.rb
It seems that
authorize!
only works on a single instance, not an array. Here's how I got around that with Rails 3.2.3 and CanCan 1.6.7.The basic idea is to count the total records that the user is trying to delete, count the records that are
accessible_by (current_ability, :destroy)
, then compare the counts.If you just wanted an array of records that the user is authorized to destroy, you could use the array returned by
accessible_by (current_ability, :destroy)
. However I'm usingdestroy_all
, which works directly on the model, so I wound up with this count-and-compare solution.It's worthwhile to check the development log to see how the two
SELECT COUNT
statements look: the second one should addWHERE
phrases for the authorization restrictions imposed by CanCan.My example deals with deleting multiple messages.
ability.rb
messages_controller.rb