It would be bad if you could edit and delete posts with others in a web application. Therefore, we will implement a process to prevent others from editing or deleting posts in the login function. In this article, we assume a simple bulletin board site. Imagine you have a Message model or a messages controller.
Prepare a helper in $ rails g helper sessions and implement current_user and logged_in?. This is not the main part to explain this time, so I will leave it as a brief explanation.
app/helpers/sessions_helper.rb
module SessionsHelper
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
!!current_user
end
end
def current_user is a method to get the currently logged in user.
@current_user ||= User.find_by(id: session[:user_id])Is
If the current login user is assigned to @ current_user → Do nothing.
If the current login user is not assigned to @ current_user → Get the login user fromUser.find_by (...)and assign it to @ current_user.
def logged_in? Returns true if the user is logged in, false if the user is not logged in.
Let's think about the controller.
app/contorollers/messages_controller.rb
class MessagesController < ApplicationController
before_action :correct_user, only: [:edit, :destroy]
#Omission
private
def correct_user
@message = current_user.messages.find_by(id: params[:id])
unless @message
redirect_back(fallback_location: root_path)
end
end
end
before_action executes the correct_user method before the edit and destroy actions are executed.
The correct_user method checks to see if the Message you are trying to edit or delete is owned by the logged-in user.
@message = current_user.messages.find_by (id: params [: id]) is searching only for the logged-in user's Messages.
If @ message is found, nothing is done here and the edit and destroy actions are taken.
If not found, unless @ message is used to determine nill andredirect_back (fallback_location: root_path)is executed.
redirect_back (fallback_location: root_path) redirects to the previous page.
For example, if you edit the Message of another person with message # index, return it to message # index, and if you delete the Message of another person with message # show, return it to messsage # show.
When unless @ message is executed (returning to the previous page), the edit action and destroy action are not executed.
In this way, we were able to prevent others from editing or deleting posts posted by others.
that's all.
[Redirect to previous page] (https://railsdoc.com/page/redirect_back)
Recommended Posts