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

后端 未结 9 612
鱼传尺愫
鱼传尺愫 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:56

    cancan is difficult and complicate i have coding is_onwer method it's very simple, easy

    https://gist.github.com/x1wins/0d3f0058270cef37b2d3f25a56a3745d

    application controller

     def is_owner user_id
        unless user_id == current_user.id
          render json: nil, status: :forbidden
          return
        end
      end
      def is_owner_object data
        if data.nil? or data.user_id.nil?
          return render status: :not_found
        else
          is_owner data.user_id
        end
      end
    

    your controller

      before_action only: [:edit, :update, :destroy] do
        is_owner_object @article ##your object
      end
    

提交回复
热议问题