3

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?

almo
  • 6,107
  • 6
  • 43
  • 86

1 Answers1

0

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.

Sean Huber
  • 3,945
  • 2
  • 26
  • 31
  • But there is no model 'User'. – almo Mar 16 '17 at 17:40
  • Use a different model or class then. It doesn't really matter because you aren't authorizing against a particular instance. – Sean Huber Mar 16 '17 at 17:41
  • According to https://stackoverflow.com/questions/34763269/adding-a-controller-without-corresponding-model-while-using-cancancan you might want to try to use `false` as passed class value. – psychoslave Apr 30 '20 at 14:57