简体   繁体   中英

CanCanCan for custom controllers with not models

I know how to restrict access for RESTful applications with CanCan in Rails 5.

Some of my actions and controllers are not RESTful.

For example I have a report_controller with a user_report method. 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?

In ability.rb define a custom ability like this:

can :view_reports, MyClass

In your user_report action, manually authorize against that ability:

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

Also, remove load_and_authorize_resource from ReportController since you are invoking authorize! directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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