It is a memorandum.
MacOS Catalina ruby 2.6.5p114 Rails 6.0.3.4 Introduced devise (using helper method called authenticate_user!)
hoges_controller.rb
class HogesController < ApplicationController
  before_action :authenticate_user!, only: [:edit]
  before_action :specified_hoge, only: [:edit, :update]
  before_action :specified_user, only: [:edit]
(Omitted)
  def edit
  end
  def update
    if @hoge.update(hoge_params)
      redirect_to root_path
    else
      render :edit
    end
  end
  private
  def hoge_params
    params.require(:hoge).permit(:text).merge(fuga_id: params[:fuga_id], user_id: current_user.id)
  end
  def specified_hoge
    @hoge = Hoge.find(params[:id])
  end
  def specified_user
    redirect_to root_path unless @hoge.user.id == current_user.id 
  end
end
Of the above, the point is here ↓
hoges_controller.rb
  before_action :specified_user, only: [:edit] 
hoges_controller.rb
  def specified_user
    redirect_to root_path unless @hoge.user.id == current_user.id 
  end
Using before_action
By doing so, even if another user manually rewrites the URL and tries to move to the edit page, it can be redirected to the home screen.
In this case, if the user id stored in the hoges table and the currently logged-in user id do not match, you can transition to root_path.
Recommended Posts