简体   繁体   English

CanCanCan用于非模型的自定义控制器

[英]CanCanCan for custom controllers with not models

I know how to restrict access for RESTful applications with CanCan in Rails 5. 我知道如何在Rails 5中使用CanCan限制RESTful应用程序的访问。

Some of my actions and controllers are not RESTful. 我的一些操作和控制器不是RESTful。

For example I have a report_controller with a user_report method. 例如,我有一个带有user_report方法的report_controller。 There is no model directly linked to this controller/action. 没有直接链接到此控制器/操作的模型。

class ReportController < ApplicationController

  load_and_authorize_resource

  def user_report

  end

end

How can I define an ability in my ability.rb file to restrict access to this action? 如何在ability.rb文件中定义一种能力来限制对此操作的访问?

In ability.rb define a custom ability like this: ability.rb定义一个这样的自定义能力:

can :view_reports, MyClass

In your user_report action, manually authorize against that ability: user_report操作中,手动授权该功能:

def user_report
  authorize! :view_reports, MyClass
  # ...
end

Also, remove load_and_authorize_resource from ReportController since you are invoking authorize! 此外,从ReportController删除load_and_authorize_resource ,因为您正在调用authorize! directly. 直。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM