Download (30.2 MB, 15:57)
Alternativer Download für iPod & Apple TV (20.3 MB, 15:57)
Resourcen:
- Episode 160: Authologic
- Episode 188: Declarative Authorization
- Episode 189: Embedded Association
- Full Episode Source Code
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]
<!– articles/show.html.erb –>
<p>
<% 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 %>
</p>
…
<p>
<% 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 %>
</p>
<!– articles/index.html.erb –>
<% if can? :create, Article %>
<p><%= link_to "New Article", new_article_path %></p>
<% end %>
[/html]