Prevent other users from going to the post edit screen

environment

・ Rails 5 -Implemented login function using device

Prevent users who are not logged in from going to the post edit screen

Change the display screen depending on whether you are logged in or not

view.rb


<% if user_signed_in? %>

If you are not logged in, jump to the login screen

controller.rb


before_action :authenticate_user!

Prevent other users from going to the post edit screen

If you write it only on the view side, you can change it by hitting the url directly, so write it on the controller side as well.

controller.rb


@book = Book.find(params[:id])
  if @book.user == current_user
    render "edit"
  else
    redirect_to books_path
  end

view.rb


<% if @book.user == current_user %>
  〜〜〜〜〜
<% end %>

Different way

controller.rb


  before_action :ensure_correct_user, only: [:edit, :update]

  def ensure_correct_user
    unless @user == current_user
      redirect_to user_path(current_user)
    end
  end

if statement → If the evaluation is true(true)If so, do ○○ unless statement → If the evaluation is false(false)If so, do ○○

Finally

Since the author is a beginner, I think there are some mistakes and lack of explanation. I would appreciate it if you could point out in that case.

References

https://qiita.com/tobita0000/items/866de191635e6d74e392

Recommended Posts

Prevent other users from going to the post edit screen
How to prevent users who are not logged in from transitioning to the new or edit page
From the introduction of devise to the creation of the users table
[Rails] How to prevent screen transition
Introduction to Ruby (from other languages)
The road from JavaScript to Java
Use the permutation method to make all the default users follow each other
Prevent login users from transitioning to a specific page by entering a URL
Investigate the replacement from Docker to Podman.
[Ruby] From the basics to the inject method
Ruby from the perspective of other languages
How to pass the value to another screen
Fix the view screen of the post page