Zeroing dependent objects in ActiveRecord

:dependent => :nullify

Why do I want to collapse dependent objects, since I do not see the goal by orphaning database records.

+6
source share
2 answers

Zeroing is only useful in special cases; let's say, for example, you have several projects that may or may not be examined by one and only one agent (therefore, its foreign key field that refers to the agent may be null). If the agent refuses all polls that he processes (let him be fired), you do not want to destroy the project record, but you cannot allow him to refer to the agent record that will no longer exist, so you will cancel his foreign key field.

+18
source

, . , , ( -). , , , , , , . , , 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

StoreItem Promotion StoreItem, , , StoreItem , .

0

All Articles