Check if current_user is the owner of a resource and allow edit/delete actions

后端 未结 9 610
鱼传尺愫
鱼传尺愫 2021-02-02 00:02

Example:

User A (id=10) has created a photo resource

photo: (id: 1 user_id = 10, url: \"http://...\")
         


        
9条回答
  •  灰色年华
    2021-02-02 00:43

    Check this railscasts,

    http://railscasts.com/episodes/192-authorization-with-cancan

    Complications you will run into,

    1. When you want cancan authorization on User Model that Devise gem is using for authentication

    2. When you want to store your Roles in the Database

    3. When you want to assign Permissions to the Roles as an Admin from the webUI

    4. and more ..

    Please comment if you want any of those features, I will be happy to help, because I recently did them with great help from others and its always amazing to pass it on.

    A sample Ability for your resources can be like as follows,

    class Ability
      include CanCan::Ability
    
      def initialize(user)
    
          user ||= User.new # guest users
          send(user.role.name)
    
            if user.role.blank?
              can :read, User #for guest without roles
            end
    
      end
    
      def man
        can :manage, Photo
      end
    
    
      def boy
        can :read, Photo
      end
    
      def kid
        can :read, Article
      end
    
    end
    

提交回复
热议问题