[RUBY] [Rails] [Parent-child relationship] I want to register the foreign key in the child with nil when the parent is deleted.

Overview

When building the following parent-child relationships with reference When deleting the data of the parent model, I want to register the foreign key with nil without deleting the child product data, but when I delete the parent from the console, an error occurs and I do not know how to deal with it. is. -Parent model: "Category" ・ Child model: "Product"

20201211121059_create_products.rb


  t.references :category, null: false, foreign_key: true

Practice

It was carried out with reference to the following articles. optional: How to allow nil if set to true https://techtechmedia.com/optional-true-rails/#optional_true https://qiita.com/takuyanin/items/6f6be86d1265be21bf9e

Like this, I added dependent and optionl options to has_many and belongs_to.

catedory.rb


class Category < ApplicationRecord
  has_many :products, dependent: :nullify
end

product.rb


class Product < ApplicationRecord
  belongs_to :category, optional: true
end

In this state, register parent and child data from the console.

Example category = Category.create!(....) category.products.create!(....)

Execute Category.destroy_all as a trial. The child's foreign key is registered as nil, right? I get the following error and have trouble dealing with it.

ActiveRecord::NotNullViolation: Mysql2::Error: Column 'category_id' cannot be null

Also, when creating a new child model data with the foreign key nil, the error is different depending on whether optional: true is set/not set.

  • At the time of setting ActiveRecord::NotNullViolation: Mysql2::Error: Field 'category_id' doesn't have a default value
  • Not set ActiveRecord::RecordInvalid: Validation failed: Category must exist

Optional: true in the first place? If set to true, validation can be passed even if the foreign key does not contain a value. ↑ ** In other words, the problem is validation ** (If the default is not set, it is false, so validation is executed.)

To the solution

(Rails db: rollback is also possible with up, down notation)

class ChangeReferencesIdToProducts < ActiveRecord::Migration[6.0]
  def up
    change_column :products, :category_id, :bigint, null: true
  end
  
  def down
    change_column :products, :category_id, :bigint, null: false
  end
end

It was caused by null: false, so by changing it to null: true The child's foreign key is now registered with nil even if the parent is deleted.

I hope it helps someone.

Recommended Posts

[Rails] [Parent-child relationship] I want to register the foreign key in the child with nil when the parent is deleted.
[Java] I want to perform distinct with the key in the object
[Ruby + Rails] When you want to register in Mailchimp's mail list together with user registration
After posting an article with Rails Simple Calendar, I want to reflect it in the calendar.
How to rename a model with foreign key constraints in Rails
[Rails] I want to add data to Params when transitioning with link_to
How to write the view when Vue is introduced in Rails?
I want to get the IP address when connecting to Wi-Fi in Java
I want to display an error message when registering in the database
I want to introduce the committee with Rails without getting too dirty
[Ruby] How to prevent errors when nil is included in the operation
[Rails] I want to reset everything because the data in the local environment is strange! What to do before that
[Rails / ActiveRecord] I want to validate the value before the type is converted (_before_type_cast)
[Rails] How to register multiple records in the intermediate table with many-to-many association
I want to play with Firestore from Rails
[Rails] I want to load CSS with webpacker
I want to get the value in Ruby
I want to solve the problem that JS is not displayed properly unless reloaded when transitioning with Turbolinks: link_to
I want to change the path after new registration after logging in with multiple devises.
[Rails] I want to display the link destination of link_to in a separate tab
I want to hit the API with Rails on multiple docker-composes set up locally
I want to embed any TraceId in the log
I want to use a little icon in Rails
I want to dark mode with the SWT app
I want to authenticate users to Rails with Devise + OmniAuth
I want to define a function in Rails Console
[Rails] What to do when rails db: migrate cannot be done because there is no table referenced by the foreign key
I want to fetch another association of the parent model from the intermediate table with has_many
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
How to solve the problem when the value is not sent when the form is disabled in rails and sent
I want to recreate the contents of assets from scratch in the environment built with capistrano
[Rails] What to do when the view collapses when a message is displayed with the errors method
I want to set the conditions to be displayed in collection_check_boxes
[Rails] [bootstrap] I want to change the font size responsively
I want to push an app made with Rails 6 to GitHub
I want to create a form to select the [Rails] category
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to distinct the duplicated data with has_many through
I want to transition to the same screen in the saved state
Things to keep in mind when using Sidekiq with Rails
[Rails] How to write user_id (foreign key) in strong parameter
I want to pass the startup command to postgres with docker-compose.
I want to simplify the conditional if-else statement in Java
When I try to use the AWS SDK with Ruby + Lambda, `sam local` is messed up.
What to do when you want to know the source position where the method is defined in binding.pry
I want to make the frame of the text box red when there is an input error
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.
When requested access to the resource is denied when pushing with Docker
When I try to put centos in VMware, pane is dead
ProxyFactory is convenient when you want to test AOP in Spring!
I want to add a browsing function with ruby on rails
I tried to sort the data in descending order, ascending order / Rails
I want to return to the previous screen with kotlin and java!
I want to avoid OutOfMemory when outputting large files with POI
[rails] How to display parent information in child view in nested relationships
I tried to implement the image preview function with Rails / jQuery
If you want to include the parent class in Lombok's @builder
How to output the value when there is an array in the array
I tried to understand how the rails method "redirect_to" is defined
What to do if Cloud9 is full in the Rails tutorial