My name is yuki. Thanks to DMMWEBCAMP, I am now working as a WEB engineer, gathering my friends to develop services, tutoring programming, and enjoying my engineer life every day.
We also provide support and error questions for those who are aiming from inexperienced, so if you are interested, please contact DM.
This time, I will explain the function that does not allow others to edit your own posts, which is common in CRUD apps with authentication function.
--Those who are familiar with crud apps --Those who are creating a simple Rails app --Those who are new to Rails or have a short period of time and are currently learning --Authentication settings and implementation of crud function have been completed with devise etc.
Implementation of a function to redirect to a list page etc. when the poster and editor are different when entering the URL to edit the post in solid
# post/1/Enter a URL such as edit
#If the poster and editor are different/Redirect to posts
"When you try to edit someone else's post, redirect it" means that when you try to edit, you must ** call that function **. First, let's create a situation where a certain process can be read when trying to edit or update.
posts_controller.rb
class PostssController < ApplicationController
before_action :correct_user, only: [:edit, :update]
#Omission
def edit
@book = Post.find(params[:id])
end
end
before_action
is explained in an easy-to-understand manner in this article. In other words, it always executes the specified method before the specified action.
This time, before edit and update… correct_user
… that is, we are calling a method to check if we are the correct user.
posts_controller.rb
#Omission
private
def correct_user
@post = Post.find(params[:id]) #Identify Post based on id
@user = @post.user #Identify the User associated with the identified Post and@Put in user
if current_user != @user #With the currently logged in user (editor)@If the user (poster) is different
redirect_to posts_path #Redirect to list page
end
end
As I wrote in the comment, it looks like this.
Since there were many articles that could be implemented by pasting this, I tried to summarize "why it happens". We hope for your reference.
Recommended Posts