[Rails] dependent settings

Purpose of this post

・ Minutes about Rails.

Teaching materials used for learning

I have summarized it with reference to the following two teaching materials of Udemy. ・ ["Introduction to Ruby on Rails for the first time-Learn Ruby and Rails from the basics and publish web applications on the net"](https://www.udemy.com/course/the-ultimate-ruby-on-rails-bootcamp/) ・ ["Rails engineer training course taught by full stack engineers"](https://www.udemy.com/course/rails-kj/)

○ dependent setting

-In the one-to-many model relationship, if the column of model (1) is deleted, the column of model (many) associated with that column becomes unnecessary. -There are the following two dependent settings that automatically delete this. -In both cases, add a description to the model (1) file.

○dependent: :delete_all

model(1).rb


class model(1) < ApplicationRecord
has_many :model(Many), dependent: :delete_all
end

-Delete model1 = Linked data will also be deleted at the same time ・ When the parent is deleted, the children are automatically deleted. -Example): When the column information of the parent question is deleted, the column information of the answer associated with it is also deleted.

○dependent: :destroy

model(1).rb


class model(1) < ApplicationRecord
has_many :model(Many), dependent: :destroy
end

-The same process as delete_all is performed, but the objects are deleted one by one. -Performance is lower than delete_all ・ If there are two or more layers of association, you may not be able to do it without using this.

○ Effective range of dependent

-The linking automatic deletion function is valid only during the destroy action. -It is necessary to change the delete method of the controller to the destroy method.


Recommended Posts

[Rails] dependent settings
[Rails] Complete routing settings
[Rails] Validation settings and Japanese localization
[Rails g.error]
Rails Review 1
RuboCop settings
Rails API
Rails migration
[Rails] first_or_initialize
About Rails 6
Rails foundation
Rails memorandum
rails tutorial
rails tutorial
rails tutorial
[Rails] devise
rails tutorial
Ruby settings 1
rails tutorial
Rails Tips
rails method
rails tutorial
[Rails] ActiveRecord
[Rails] form_with
Rails Review 2
Validation settings for Ruby on Rails login function