:dependent => :nullify
Why would I want to nullify dependant objects, since I don't see a purpose by orphaning database records.
dependent: :destroy Rails, when attempting to destroy an instance of the Parent, will also iteratively go through each child of the parent calling destroy on the child. The benefit of this is that any callbacks and validation on those children are given their day in the sun.
Dependent is an option of Rails collection association declaration to cascade the delete action. The :destroy is to cause the associated object to also be destroyed when its owner is destroyed.
The dependent: option which is built into Rails allows us to specify what happens to the associated records when their owner is destroyed. Until now, the dependent: option accepted :destroy , :delete_all amongst other values.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
Nullifying is only usefull in very specific cases ; let's say for example you have some projects, which may or may not be surveyed by one and only one an agent (so its foreign key field referencing the agent can be null). If the agent abandons all the surveys he handles (let's say he's been fired), you don't want to destroy the project record, but you can't let it reference to an agent record that won't exist anymore, so you nullify its foreign key field.
Consider the case where we have a number of stores and items. Each item can have many stores and each store can have many items so they are linked with a join table (or cross table). Lets say that each store can also do its own promotion containing a bundle of items, the place we could store this is on the join table optionally belonging to a promotion. At the end of the promotion it can be destroyed but we want to retain the link between stores and items and so we'd nullify the promotion_id
.
class Store
has_many :store_items, dependent: :destroy
has_many :items, through: :store_items
end
class Item
has_many :store_items, dependent: :destroy
has_many :items, though: :store_items
end
class Promotion
has_many :store_items, dependent: :nullify
end
class StoreItem
belongs_to: :item
belongs_to: :store
belongs_to: :promotion, optional: true
end
Ideally we might allow the StoreItem
to have many Promotion
s and then store date time's on the join table so we know when the StoreItem
was in a promotion or not but that might be overcomplicating things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With