almo
almo

Reputation: 6387

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?

Upvotes: 4

Views: 2112

Answers (1)

Sean Huber
Sean Huber

Reputation: 3985

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.

Upvotes: 0

Related Questions