Ruby on Rails - getting started with cancan in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
what is cancan in ruby on rails?
CanCan is a a popular authorization library for Ruby on Rails which restricts user access to specific resources. The latest gem (CanCanCan) is a continuation of the dead project CanCan.
Permissions are defined in the Ability class and can be used from controllers, views, helpers, or any other place in the code.
Adding authorization support to an app, add the CanCanCan gem to the Gemfile:
gem 'cancancan'
Example
# app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
end
end
Then check authorization using load_and_authorize_resource to load authorized models into the controller:
class ArticlesController < ApplicationController
load_and_authorize_resource
def show
# @article is already loaded and authorized
end
end
authorize! to check authorization or raise an exception
def show
@article = Article.find(params[:id])
authorize! :read, @article
end
- can? to check if an object is authorized against a particular action anywhere in the controllers, views, or helpers
<% if can? :update, @article %>
<%= link_to "Edit", edit_article_path(@article) %>
<% end %>
Note: This assumes the signed user is provided by the current_user method