Managing associated objects

Bookmark and Share

Most of the rails applications build, works around databases. And the most commonly used relationship in database is the one to many relationship. In rails its represented as has_many on the parent side and belong_to on the child’s side. Now, as we write the relationship we also need to make sure what should be done to the children when the parent is destroyed. Else we will be stuck with a lot of orphan records once the parent is destroyed.

So to avoid that, we pass in the dependent attribute at the parents side, like below:

has_many :users, dependent: :destroy

The above code will run the destroy method on the children, when the parent is destroyed.

Like destroy, rails provides a total of five options. They are

  • 1: destroy – run the destroy method on all the associated objects, there by also triggering the callbacks
  • 2: delete_all – causes the associated methods to be deleted directly from DB, no callbacks triggered. This would be a faster, compared to :destroy, to delete the associated models.
  • 3: nullify – sets the foreign key to be set to NULL. no callbacks triggered. We use it when we don’t want the children to be …
Read More

after_create vs after_save vs after_commit

after_save, after_create and after_commit are called active record call backs in rails. They get executed when we work on the database, similarly we also have before_* callback and callbacks on destroy as well. In this article I will explain you about the difference between *_save, *_create and *_commit callbacks.

The purpose of each as per rails docs:

Is called after on new objects that haven‘t been saved yet (no record exists)

Is called after (regardless of whether it‘s a create or update save)

Is called after the database transaction is completed.

Now to explain the real difference between the three, we must first explain about database transaction. They are a protective block around a group of sql statements, that are permanent only if all of them succeed in a single atomic statement.

When rails execute a create, the after_save and after_create would be called within the transaction block of the create statement. So they will be executed before executing the sql statement to make permanent changes in the DB. If the query fails, then no change will happen to the DB, but we would have executed the instructions of the after_create and after_save block.

Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.

Read More