Home Authentication with Devise and cancancan in Rails
Post
Cancel

Authentication with Devise and cancancan in Rails

To use the cancancan gem with devise in a Ruby on Rails app, you will need to do the following:

First, you need to add the cancancan gem to your Gemfile and run bundle install.

Then create a Ability model by running the following command:

1
rails g cancan:ability

This will create a new file at app/models/ability.rb that contains the Ability class.

In the Ability class, define the permissions for different user roles. For example:

1
2
3
4
5
6
7
8
9
10
11
class Ability
  include CanCan::Ability

  def initialize(user)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

In your controllers, use the load_and_authorize_resource method to load and authorize the resource. For example:

1
2
3
4
5
6
7
class PostsController < ApplicationController
  load_and_authorize_resource

  def show
    # The @post instance variable has already been loaded and authorized
  end
end

In your views, use the can? method to show or hide content based on the user’s permissions. For example:

1
2
3
<% if can? :update, @post %>
  <%= link_to 'Edit', edit_post_path(@post) %>
<% end %>

I hope this helps! Let me know if you have any questions.


This post is licensed under CC BY 4.0 by the author.