开发者

Nullifying dependent objects in ActiveRecord

开发者 https://www.devze.com 2023-04-04 03:02 出处:网络
:dependent => :nullify Why w开发者_如何学JAVAould I want to nullify dependant objects, since I don\'t see a purpose by orphaning database records.Nullifying is only usefull in very specific cases
:dependent => :nullify

Why w开发者_如何学JAVAould I want to nullify dependant objects, since I don't see a purpose by orphaning database records.


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 Promotions 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消