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

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

    So you are using gem devise.

    This gem provides the current_user for the currently logged in user.

    In your PhotosController#edit method. I'd do something like below.

    def edit
      @photo = Photo.find(params[:id])
      redirect_to root_path, notice: 'Thou Shalt Nought duuu dat :(' unless current_user.id == @photo.user_id
      ...
    end
    

    This method is cheaper because you already have 2 objects to compare instead of running a query in the comparison.

提交回复
热议问题