[RUBY] Processing when an ID that does not exist in the database is entered in the URL

Main story

The data registered in the database is given the ID of the primary key, but if that data is deleted, that ID will no longer exist. There is a : id in the URL of the product detail page and the member detail page, and by changing this number, the detail page corresponding to the ID of that number will be displayed, but if an ID that does not exist is entered In case of

ActiveRecord::RecordNotFound
Couldn't find model name with'id'=Entered number

Error occurs.

The process to be performed this time is "Display if the ID exists, and redirect if it does not exist".

environment

Ruby 2.5.7 Rails 5.2.4

Processing procedure

This time, we will define an action in application_controller and set that action as befor_action in each controller you want to redirect. As for the situation, it is assumed that the process is when the product ID is entered in the URL on the product details page.

application_controller.rb


class ApplicationController < ActionController::Base

  def exist_item?
    unless Item.find_by(:id params[:id])
      redirect_to root_path
    end
  end

Use the unless statement to perform the processing inside when the conditional expression is false. In this case, the find_by method is used to search for the entered numerical value (params [: id]) from the item IDs, and whether or not it hits is a condition, and if it does not hit (= false) ) Means that the internal process redirect_to root_path is executed.

Next, set ʻexist?Defined in application_controller.rb tobefore_action` in the controller of the product.

items_controller.rb


class ItemsController < ApplicationController
 
  #In the URL:Specify an action including id
  before_action :exist_item?, only[:show, :edit, :update, :destroy]
  ...

  def show
    ...
  end

  ...

end

At this time, the action specified by the option ʻonly:may be only: show and: editwith display, but for the time being, add: update and: destroyas well. (It is not necessary, but if you forcibly change the parameters in the form and submit it, the error at the beginning will be displayed.) This will perform an action (ʻexist_item?) That verifies that the ID of the entered item exists before each action.

Summary

It is expected that the display speed, which was a weak point before the correction, will be greatly improved.

I would like to continue to verify the comments I received from time to time!

Thank you for reading until the end!

The article before correction is as follows, but it is deprecated.

Processing procedure (* not recommended)

This time, we will define an action in application_controller and set that action as befor_action in each controller you want to redirect. As for the situation, it is assumed that the process is when the product ID is entered in the URL on the product details page.

application_controller.rb


class ApplicationController < ActionController::Base

  def exist?
    Item.all.each do |item|
      if item.id == params[:id].to_i
        return
      end
    end
    redirect_to root_path
  end

end

First, use the each statement to get all the product information in order from the product table. In each, it is verified whether the ʻid of the item is the same as the entered numerical value for each round. (.To_i is used because the entered number is recognized as a string type and must be aligned with the same integer type as ʻitem.id.

item.id = 0
params[:id] = "0"
if item.id == params[:id] => false

If the item ID and the entered numerical value (params [: id]) match in each statement, the processing in ʻif, returnis performed. When areturn is made, the program will skip it and end the action, so the redirect_to root_pathwill not be executed. On the contrary, if the each statement ends and the numerical value entered in it and the item ID never match, the subsequentredirect_to root_path` is executed to redirect to any page.

items_controller.rb


class ItemsController < ApplicationController
 
  #In the URL:Specify an action including id
  before_action :exist?, only[:show, :edit, :update, :destroy]
  ...

  def show
    ...
  end

  ...

end

Next, set ʻexist?Defined in application_controller.rb tobefore_action in the controller of the product. At this time, the action specified by the option ʻonly: may be only : show and: edit with display, but for the time being, add : update and: destroy as well. (It is not necessary, but if you forcibly change the parameters in the form and submit it, the error at the beginning will be displayed.) This will perform an action (ʻexist? `) That verifies that the ID of the entered item exists before each action.

Weaknesses

This method takes longer to process as the number of records (the number of products in this case) increases. If there are 1,000 products, each statement will be repeated up to 1,000 times, so the display of details pages etc. will be considerably heavy.

There should be another good way, so I will update it as soon as I find it ┏ ○ I would appreciate it if you could let me know in the comments!

Recommended Posts

Processing when an ID that does not exist in the database is entered in the URL
Handling when calling a key that does not exist in hash
What to do when "relation" hibernate_sequence "does not exist" in the ID column of PostgreSQL + JPA
When the project is not displayed in eclipse
An active hash that can be treated as data even if it is not in the database
What to do when rails db: seed does not reflect in the database
Guidelines for writing processing when a value exists / does not exist in Java Optional
Docker does not work when DOCKER_HOST is specified in WSL2
When running annotation processing in the IDE, the annotation information whose Retention is SOURCE may not be obtained.
[Gradle] The story that the class file did not exist in the jar file
How to output the value when there is an array in the array
How to solve the problem that it is not processed normally when nesting beans in Spring Batch
A program that determines whether the entered integer is close to an integer
[Rails] About the error that the image is not displayed in the production environment
Ignore parameters that do not exist in the model with ObjectMapper # readValue
I want to display an error message when registering in the database
Precautions when specifying the URL in render
Continuation ・ Active hash that can be handled as data even if it is not in the database ~ Display
If the JDK version is correct in Eclipse but an error occurs or the compiler does not work properly
In WSL2, when I did `docker-compose up`, I got an error saying that the sh file was not found.
[JPA] Compare table1 and table2 to get and update data that does not exist in table2.
Setting method that the size does not change even if CSS is changed
How to set when "The constructor Empty () is not visible" occurs in junit
Escape processing when creating a URL in Ruby
Regarding hash key and value mapping
Does the escape sequence (\) not work? (for Mac)
The public key for jenkins-2.249.1-1.1.noarch.rpm is not installed
Guidelines for writing processing when a value exists / does not exist in Java Optional
The problem that the JDK set in JAVA_HOME does not appear even if java -version is performed at the command prompt
[Error] ActiveRecord :: NoDatabaseError FATAL: database does not exist
Does not recognize the library when implementing jcaptcha
Ebean.update () is not executed in the inherited model.
[Railways] Railways does not work when the RubyMine project root is other than the Rails root directory.
About the "Oops VFS connection does not exist" error and solution in AWS Cloud9
[Android Studio] About the matter that the design view is not displayed when using TextClock
The story when the container does not start up with docker-compose up and an error occurs
"Do not show again" check does not work in the warning dialog when starting applet
Customize the display when an error such as 404 Not Found occurs in Spring Boot
[Note] When the page access speed does not increase
PATH does not pass ... The cause is the character code
Set the root URL when starting tomcat in intelliJ
Correspondence when Ruby version does not switch in rbenv
Code that only displays the built-in camera in Processing
[Error] The app is not displayed in the production environment
Null value is entered when assigning to an array
When the server does not start with rails s
The story that .java is also built in Unity 2018
When I run docker-compose exec in crontab, I get "the input device is not a TTY"
When a breakpoint is set in IntelliJ IDEA but it does not stop in debugging [Gradle]
How to solve the problem when the value is not sent when the form is disabled in rails and sent
When rewriting the CMD of docker image of Pod in the manifest of k8s, command is not good
What to do when Rails on Docker does not reflect controller changes in the browser
[Rails] How to temporarily save the request URL of a user who is not logged in and return to that URL after logging in
Java learning_Behavior when there is a method with the same name as a field with the same name in two classes that have an inheritance relationship