[Rails] I want to reset everything because the data in the local environment is strange! What to do before that

Introduction

I saw the following Qiita article.

The idea of cutting off the source when the error is not resolved -Qiita

I would like you to read the above article for details, but in a simple summary, "If the data in the local environment becomes strange, let's recreate the database (after confirming that it is okay to erase the data)" is.

However, I personally thought, "Well, it's not so good," so I decided to write a reply comment. When I started writing comments, it became quite long, so I decided to make it an independent article. That is this article.

That's why I want to reset everything because the data in the local environment is strange! Here's what you need to do before you think.

I want to reset everything because the data in the local environment is strange! What to do before that

(Note: The following content was originally written as a reply comment to Qiita article at the beginning. Please read on that assumption.)

Resetting the database is effective when "it is okay to erase all the data", but it cannot be used otherwise. Rails apps developed as a personal hobby may be good, but Rails apps developed at work often have a lot of "test data that I have used often" even though it is a local environment. It means, "I can't erase all of this." Also, if the same problem occurs in the production environment instead of the development environment, the strategy of "erasing all data" cannot be used.

Furthermore, it becomes difficult to investigate the cause of why the data that caused the error occurred if all the data was erased.

For the reasons mentioned above, "erasing all data" should really be left as a last resort, and as much research and action as possible should be done before erasing the data.

I would take the following remedies.

Investigate the cause of the defect and determine whether the data is abnormal or not

First, determine the cause of the problem. In this article, it seems that the cause is that post.user is nil.

https___qiita-image-store.s3.ap-northeast-1.amazonaws.com_0_688029_480b986b-36d4-66fd-60a6-7f1dcef94075.png

Then determine if the condition is valid. When post.user is nil, it means that there is no contributor associated with the post. If you think in common sense, I think this is an unlikely situation (= data abnormality).

Find out the cause of the data error and correct the code if necessary (prevention of recurrence)

Then, think about the cause, "Why did a post without a poster come out?" If you don't figure out the cause, even if you recreate the database and get no error, after a while, "posts without posters" may pop up again.

If you normally operate the screen and you can post without a poster, it is a bug, so be sure to modify the code so that the poster is set so that the bug does not recur.

The possible causes and remedies are listed below.

ʻOptional: if true` is attached

In recent Rails, the related record defined by belongs_to is required by default, so I think it is unlikely, but if it has ʻoptional: true, remove it. That way, if you try to save a Post with ʻuser in nil, you will get a validation error.

app/models/post.rb


 class Post < ApplicationRecord
-  belongs_to :user, optional: true
+  belongs_to :user
 end

If you later add the ʻuser_id` column to the posts table

Or maybe the Post model was created first, and then some time later another migration added ʻuser_id` to the posts table. In this case, after executing migration, it is necessary to associate some User record with the existing Post record and save it (modify the existing data). If you forget this correspondence, "posts without posters" will be born.

If the User record has been deleted

Perhaps the most probable cause is "I deleted the poster's User record after creating the Post record". in this case,

--Do not allow user records with associated Post records to be deleted --Or, if you delete the User record, delete the related Post record as well. --Alternatively, after accepting posts without posters as normal data, a display like "Unsubscribed user" is displayed on the screen.

Such a coping method can be considered. The first two can be set with Rails' dependent option. See the following articles for details.

Difference between: dependent:: restrict \ _with \ _ error and: restrict \ _with \ _exception -Qiita

This is the only cause that comes to my mind, but if I find another cause (= defect) that "this was the cause", I will modify the program so that "posts without posters" will not be created again in the future.

If recurrence prevention measures are taken, correct existing abnormal data

If you can create a situation where strange data is not generated, it is time to correct the existing abnormal data. For example, you can set the poster for "Post without poster" by executing the following script. (This is just an example, so please modify the script as appropriate.)

user = User.first
Post.all.each do |post|
  if post.user.nil?
    post.user = user
    post.save!
  end
end

Alternatively, data correction such as deleting "posts without posters" is also an option.

Post.all.each do |post|
  if post.user.nil?
    post.destroy!
  end
end

By doing this, the poster will be linked to all posts, so calling post.user.image_name should not cause an error.

If the data is not abnormal, correct the code appropriately

If the situation that "there is no contributor associated with the post" is not a problem (valid as a specification), it is necessary to separate the view processing depending on whether post.user is nil.

<% if post.user %>
  <%#Processing when there is a poster%>
<% else %>
  <%#Processing when there is no poster%>
<% end %>

Summary

If you deal with it in this way, you can avoid taking the measure of "erasing all data". Or rather, I think it's usually appropriate to take this approach, except when you say, "I'm just making it in my local environment as a personal hobby."

Recommended Posts

[Rails] I want to reset everything because the data in the local environment is strange! What to do before that
What to do if Cloud9 is full in the Rails tutorial
[Programming beginner] What to do when rails s becomes an error in the local development environment
[Rails / ActiveRecord] I want to validate the value before the type is converted (_before_type_cast)
What to do about "A server is already running ..." that happened without turning off the rails server in the terminal
I tried using Docker because I don't want to pollute the local environment in Microsoft Teams tab development of MS Learn
I tried to sort the data in descending order, ascending order / Rails
What to do if the Rails page doesn't appear in Rails tutorial 1.3.2
I want to display the images under assets/images in the production environment
The story that I struggled because I couldn't do "Rails db: migrate".
[Rails] How to reset the database in production environment (Capistrano version)
What to do when you want to know the source position where the method is defined in binding.pry
After learning Progate, I tried to make an SNS application using Rails in the local environment
[Rails] About the error that the image is not displayed in the production environment
[Rails] Reset the database in the production environment
[Rails] [Parent-child relationship] I want to register the foreign key in the child with nil when the parent is deleted.
I want to create the strongest local development environment using VSCode Remote Containers
Androd: What to do about "The Realm is already in a write transaction in"
I tried to organize the session in Rails
I want to get the value in Ruby
I want to get the information of the class that inherits the UserDetails class of the user who is logged in with Spring Boot.
What to do when ‘Could not find’ in any of the sources appears in the development environment with Docker × Rails × RSpec
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
How to install Docker in the local environment of an existing Rails application [Rails 6 / MySQL 8]
For those who want to use MySQL for the database in the environment construction of Rails6 ~.
[Rails] How to delete production environment MySQL data after putting it in the development environment
What to do when "Fail to load the JNI shared library" is displayed in Eclipse
What to do when Address already in use is displayed after executing rails s
[Rails] I want to display the link destination of link_to in a separate tab
What to do if the Rails server can't start
I want to do something like "cls" in Java
I want to embed any TraceId in the log
I want to use a little icon in Rails
What should I do to reload the updated Dockerfile?
I want to define a function in Rails Console
Note that I stumbled upon building the Rails environment
SSL in the local environment of Docker / Rails / puma
[Maven] What to do if you are asked to incorporate a jar that is not in the remote repository into the war
[Rails] What to do when rails db: migrate cannot be done because there is no table referenced by the foreign key
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
After posting an article with Rails Simple Calendar, I want to reflect it in the calendar.
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
I tried to develop the cache function of Application Container Cloud Service in the local environment
I want to recreate the contents of assets from scratch in the environment built with capistrano
What to do when Rails on Docker does not reflect controller changes in the browser
[Rails] What to do when the view collapses when a message is displayed with the errors method
[Rails] [bootstrap] I want to change the font size responsively
I want to create a form to select the [Rails] category
What I did in the version upgrade from Ruby 2.5.2 to 2.7.1
I want to distinct the duplicated data with has_many through
I want to transition to the same screen in the saved state
What to do if you can't use the rails command
I want to simplify the conditional if-else statement in Java
[Rails] What to do when the error No database selected and Unknown database appears in db: migrate
[Java] I want to check that the elements in the list are null or empty [Collection Utils]
[Rails] I can post S3 images in my local environment, but I can't switch to S3 on Heroku.
What to do if the app is not created with the latest Rails version installed when rails new
I want to import the pull-down menu items when submitting a form in Rails into CSV and display them from the DB data.
[Ubuntu 20.04] What to do if the external monitor is not recognized
I tried to summarize the words that I often see in docker-compose.yml
The story of Collectors.groupingBy that I want to keep for posterity