LuckyLuke
LuckyLuke

Reputation: 49057

Deleting objects from associations in Rails

I am learning Rails and I am reading the Beginning Rails 3 book. When you have a has_many association you automatically receives methods.

Let say user has many articles.

user.articles.delete(article)

Now that line only set the foreign key of the article to "NULL". Is it correct that you also must destroy/delete the article if you want it to disappear from the database, or is there a method that does it both?

And what happens if you destroy an article that is in a relationship with a user before you delete the association?

Upvotes: 1

Views: 586

Answers (1)

gabrielhilal
gabrielhilal

Reputation: 10769

There are some difference between delete and destroy.

The delete method essentially deletes a row.. that's it..

On the other hand, destroy allows you more options:

  • it will check any callbacks such as before_delete, or any dependencies specified on the model.
  • it will also keep the object that just got deleted in memory; So it allows you to leave a message saying for example: “Article #{article.id} deleted!!”
  • And the answer for your question: it will delete any child objects associated with the object.

So, instead of

user.articles.delete(article)

you can use

user.articles.destroy(article)

In this way you will prevent any orphaned rows on the database.

Upvotes: 2

Related Questions