简体   繁体   中英

Rails: dependent: :destroy - How does this work?

In an example where there is an association of Owner that is as fellows:

class Owner < ActiveRecord::Base
  has_many :buildings, dependent: :destroy 
end

The other side of relationship:

class Building < ActiveRecord::Base
  belongs_to :owner
end

If I were to delete an Owner, would it destroy the associated Building(s) as well? How can I specify a dependent relationship so that the owner and primary key is no longer associated with any Building(s) if I delete an Owner?

You probably want :nullify . See the Rails docs for has_many .

:dependent controls what happens to the associated objects when their owner is destroyed. Note that these are implemented as callbacks, and Rails executes callbacks in order. Therefore, other similar callbacks may affect the :dependent behavior, and the :dependent behavior may affect other callbacks.

:destroy causes all the associated objects to also be destroyed.

:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).

:nullify causes the foreign keys to be set to NULL. Callbacks are not executed.

:restrict_with_exception causes an exception to be raised if there are any associated records.

:restrict_with_error causes an error to be added to the owner if there are any associated objects.

If using with the :through option, the association on the join model must be a belongs_to , and the records which get deleted are the join records, rather than the associated records.

  1. Yes, it will delete the associated buildings as dependent :destroy specified.
  2. If you want to keep the building record, I suggest you use a join table, so that when owner is deleted, only the record in the join table is deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM