Nullifying dependent objects in ActiveRecord
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.