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:

  1. Define the association between the parent and child models using the has_many and belongs_to methods in your model files. For example, if you have a Parent model and a Child model, you would add the following code:
class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
end

class Child < ApplicationRecord
  belongs_to :parent
end
  1. In the has_many declaration in the parent model (Parent), include the dependent: :destroy option. This option tells Rails to destroy the associated child records when the parent is deleted.

  2. 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
  1. 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.