Managing associated objects

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 destroyed, and kept in our system. Usually done to keep history, or protect the associated objects referencing to the children.
  • 4: restrict_with_exception – It will raise an exception if there are associated objects. Hence also prevent the destruction of the parent.
  • 5: restrict_with_error- It will prevent the deletion of the parent, and will pass in the error that it has associated objects without raising the exception.
]]>