W
W
weare1382015-02-21 19:13:57
Ruby on Rails
weare138, 2015-02-21 19:13:57

How to use multiple roles in a cancan?

Hello guys. Such a question: I want to use three roles in the application admin, moder and client. The admin can do everything, the moderator can rub comments and posts, and the client can create posts, read and edit his comments. I used cancancan, here is the ability class

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.admin?
      can :manage, :all
    elsif user.moderator?
      can :manage, Post, Comment
    elsif user.client?
      can :create, Post
      can [:update, :destroy], Comment, user_id: user.id
    else
      can :read, :all
    end
  end
end

Everything seems to work, except that the guest still has the ability to create posts. How to fix it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim, 2015-02-21
@1kachan

test job on MLSDev?

A
Alexander, 2015-02-21
@DrunkenMaster

Obviously, explicitly handle this situation:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.persisted?
      if user.admin?
        can :manage, :all
      elsif user.moderator?
        can :manage, Post, Comment
      elsif user.client?
        can :create, Post
        can [:update, :destroy], Comment, user_id: user.id
      end
    end

    can :read, :all
  end
end

or don't do user ||= User.new, then unless user.nil?

A
Alexey, 2015-02-22
@fuCtor

Try to explicitly disable:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.admin?
      can :manage, :all
    elsif user.moderator?
      can :manage, Post, Comment
    elsif user.client?
      can :create, Post
      can [:update, :destroy], Comment, user_id: user.id
    else
      cannot :create, Post
      can :read, :all
    end
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question