Understanding how to use the cancan gem for authentication
Gemfile, add gem 'cancancan'bundle installAbility class: rails g cancan:abilitydef show
@article = Article.find(params[:id])
authorize! :read, @article
end
class ArticleController < ApplicationController
load_and_authorize_resource
def show
# @article is already loaded and authorized
end
end
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.json { head :forbidden }
format.html { redirect_to main_app.root_url, :alert => exception.message }
end
end
end
<% if can? :update, @article %>
<%= link_to "Edit", edit_article_path(@article) %>
<% end %>
# OR it can look like this:
<% if cannot? :update, @article %>
Editing disabled.
<% end %>
rails g cancan:ability
class Ability
include CanCan::Ability
def initialize(user)
if user.admin?
#only admins can change this
can :update, Article
end
# anyone can read
can :read, Article
end
end
can or cannot both take the following arguments: