Wednesday, 11 January 2017

How to use cancan in rails?

CanCan is an authorization library for Ruby on Rails which restricts what resource a given user is allowed to access.  All permissions are defined in a single location and not duplicated in controllers, views and database queries.

Step-1        Installation

Gem ‘cancancan’,’~>1.10’

Step-2        When using rails-api,you have to include the controller method for 
CanCan:

   class ApplicationController < ActionController::API
   include CanCan::ControllerAdditions
   End

Step-3        Generate the class:

      Rails g cancan:ability

      Add a new class in app/models/ability.rb with the following contents:
            
      class Ability

      include CanCan::Ability

   def initialize(user)
   End
   End

Step-4        The current user’s permission  can be checked by can?  and cannot?  methods in view and  controller.

  
 <% if can? :update, @article %>
 <%= link_to "Edit", edit_article_path(@article) %>
 <% end %>

The authorize!  method in controller will raise an exception if the user will not be able to perform the given action.

   def show
  @article = Article.find(params[:id])
  authorize! :read, @article
  end

Step-5        Handle Unauthorized Access

If the user authorization fails,a CanCan::AccessDenied  exception will be raised.You can catch this and modify its behavior in the ApplicationController.

class ApplicationController < ActionController::Base
 rescue_from CanCan::AccessDenied do |exception|
 redirect_to root_url, :alert => exception.message
 end
 end
 

 If you have any further doubts, drop us an email at info@infigic.com and we’ll get back to you with the best possible solution. Infigic is a Ruby on Rails Development Company and we are always there to solve your queries.

No comments:

Post a Comment