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

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

    I captured the exception from within a before_filter action:

    before_action :set_photo, only: [:edit, :update, :destroy]
    
    def set_photo
      @photo = current_user.photos.find(params[:id])
    
      rescue ActiveRecord::RecordNotFound
        redirect_to(root_url, :notice => 'Record not found')
    end
    

    Hope this helps someone. I'm using Rails 4 and Ruby 2.

提交回复
热议问题