ROR Cancan - Right way to set permission for user

71 Views Asked by At

I am a new ROR developer. I want to set permission for each type of user with Cancan, from lowest to highest is: guest, member, editor, admin; with higher user has all permissions lower user has. My file ability.rb as below:

  include CanCan::Ability

  def initialize(user)
    unless user
      guest_can
    else
      if user.admin?
          admin_can
      elsif user.editor?
        editor_can(user)
      elsif user.member?
        member_can(user)
      end
    end
  end

  private

  def guest_can
    can :read, Article
  end

  def member_can(user)
    # member can do whatever guest can
    guest_can
    can :create, Comment
    can [:update, :destroy], Comment, :user_id => user.id
  end

  def editor_can(user)
    # editor can do whatever member can
    member_can
    can :create, Article
    can [:update, :destroy], Article, :user_id => user.id
  end

  def admin_can
    can :manage, :all
  end
end

Could you please tell me if my code is good enough or can it cause potential problems? Thank you

0

There are 0 best solutions below