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

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

    You can make use of Rails' associations and write it like this:

    def edit
      @photo = current_user.photos.find(params[:id])
    
      # ... do everything else
    end
    

    This will only find a record when the photo with the supplied ID belongs to the current user. If it doesn't, Rails will raise a ActiveRecord::RecordNotFound exception.

    Of course, I'm assuming the current_user method is available and your User model contains the statement has_many :photos.

提交回复
热议问题