asdf

Ruby code posted
created at 16 Jan 16:53, updated at 26 Apr 12:05

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# config/environment.rb
config.gem "cancan"

# models/ability.rb
class Ability
  <b style="color:black;background-color:#ffff66">include CanCan</b>::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
934 Bytes in 2 ms with coderay