From the course: Ruby on Rails 6 Essential Training: Models and Associations

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Destroy dependent-related records

Destroy dependent-related records - Ruby on Rails Tutorial

From the course: Ruby on Rails 6 Essential Training: Models and Associations

Start my 1-month free trial

Destroy dependent-related records

- [Narrator] Active record gives us some other nice features to allow us to manage the data in our database. And one of those is that it offers to destroy dependent related records. Let me explain what I mean by that. Let's say that we have two classes, a user class and a common class. And a user is able to comment. Let's say they're commenting on a blog post, for example. So user has many comments, and every comment belongs to a user, that's the association. So we have our application running for a while, and we have users who are being created, and they're writing comments, and those are being put in the comments table, but then a user is deleted from the database. So we delete a user. Now we have comments that have a foreign key pointing to that user ID, which no longer exists. They are orphaned records. That's not great. We'd like to be able to delete those comments. Now you could write code so that every time…

Contents