This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
If you destroy a record that has_many associated records, by default, those associated records will be left in the database. Sometimes these are called "orphaned" records, because their parent record is gone. If you want associated records to be removed when their parent is removed, you can add the dependent: :destroy option to the has_many association in the model class.
If you destroy a record that has_many
associated records, by default, those associated records will be left in the database. Sometimes these are called "orphaned" records, because their parent record is gone.
Right now, if we destroy a Movie
, for example, Actor
instances belonging to that movie will be left in the database.
If you want associated records to be removed when their parent is removed, you can add the dependent: :destroy
option to the has_many
association in the model class.
class Show < ApplicationRecord
has_many :actors, as: :production, dependent: :destroy
end
class Movie < ApplicationRecord
has_many :actors, as: :production, dependent: :destroy
end
In the future, when we destroy any Movie
or Show
instance, Actor
instances belonging to that production will be removed as well.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up