Search code examples
ruby-on-railsruby-on-rails-5cancancancancan

Ruby on Rails CanCan Gem


I am a bit confused regarding CanCan Gem. I basically understand how to set up abillity.rb. For example lest say we have the following code:

// in abillity.rb

user ||= User.new

can [:update, :destroy, :edit, :read], Book do |book|
  book.dashboard.user_id == user.id
end

And then lets say we have the following books controller:

// books_controller.rb
load_and_authorize_resource

def destroy
  if can?(:destroy, @book)
    @book.destroy!
    redirect_to happy_world_path
  else
    redirect_to not_happy
  end
end

My question is: Do we need to check 'can?(:destroy, @book)'? From my understanding 'load_and_authorize_resource' will not even allow access to this method if we don't have abillity to destroy it.


Solution

  • Yo do not need to add if can?(:destroy, @book) in your action if you use load_and_authorize_resource

    Like the README say

    Setting this for every action can be tedious, therefore the load_and_authorize_resource method is provided to automatically authorize all actions in a RESTful style resource controller.

    If an user without authorization try to destroy, he get a unauthorized response ( not remember if is a 401 code)

    Maybe you can use if can?(:destroy, @book) in your views, to do no show thte destroy button. Like also in Check Abilities & Authorization section