rails delete child on parent delete
To delete a child record when a parent record is deleted in Ruby on Rails, you can make use of the dependent
option in the association declaration. Here are the steps to achieve this:
- Define the association between the parent and child models using the
has_many
andbelongs_to
methods in your model files. For example, if you have aParent
model and aChild
model, you would add the following code:
class Parent < ApplicationRecord
has_many :children, dependent: :destroy
end
class Child < ApplicationRecord
belongs_to :parent
end
In the
has_many
declaration in the parent model (Parent
), include thedependent: :destroy
option. This option tells Rails to destroy the associated child records when the parent is deleted.When you delete a parent record, Rails will automatically delete all the associated child records. For example, if you have a parent record with an
id
of 1 and it has multiple child records, you can delete it using the following code:
parent = Parent.find(1)
parent.destroy
- After executing the
parent.destroy
command, Rails will delete the parent record and all its associated child records.
By using the dependent
option with the value :destroy
, you ensure that child records are automatically deleted when the parent record is deleted. This helps maintain data integrity and prevents orphaned child records in your database.