· 2 min read

Screencast: Authorisierung mit CanCan

Download (30.2 MB, 15:57) Alternativer Download für iPod & Apple TV (20.3 MB, 15:57)

Resourcen:

Quellcode:

[bash] sudo rake gems:install [/bash]

[ruby] # config/environment.rb config.gem “cancan”

# models/ability.rb class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? :admin can :manage, :all else can :read, :all can :create, Comment can :update, Comment do |comment| comment.try(:user) == user || user.role?(:moderator) end if user.role?(:author) can :create, Article can :update, Article do |article| article.try(:user) == user end end end end end

# application_controller.rb rescue_from CanCan::AccessDenied do |exception| flash[:error] = “Access denied.” redirect_to root_url end

# articles_controller.rb load_and_authorize_resource

# comments_controller.rb possibility load_and_authorize_resource :nested => :article [/ruby]

[html]

<% if can? :update, @article %> <%= link_to “Edit”, edit_article_path(@article) %> | <% end %> <% if can? :destroy, @article %> <%= link_to “Destroy”, @article, :method => :delete, :confirm => “Are you sure?” %> | <% end %> <%= link_to “Back to Articles”, articles_path %>

<% if can? :update, comment %> <%= link_to “Edit”, edit_comment_path(comment) %> <% end %> <% if can? :destroy, comment %> | <%= link_to “Destroy”, comment, :method => :delete, :confirm => “Are you sure?” %> <% end %>

<% if can? :create, Article %>

<%= link\_to "New Article", new\_article\_path %>

<% end %> \[/html\]
Back to Blog