[英]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
.你可能想要:nullify
。 See the Rails docs for has_many
.有关has_many
请参阅 Rails 文档。
:dependent
controls what happens to the associated objects when their owner is destroyed. :dependent
控制关联对象的所有者被销毁时会发生什么。 Note that these are implemented as callbacks, and Rails executes callbacks in order.请注意,这些是作为回调实现的,Rails 会按顺序执行回调。 Therefore, other similar callbacks may affect the :dependent behavior, and the :dependent behavior may affect other callbacks.因此,其他类似的回调可能会影响 :dependent 行为,而 :dependent 行为可能会影响其他回调。
:destroy
causes all the associated objects to also be destroyed. :destroy
会导致所有关联的对象也被销毁。
:delete_all
causes all the associated objects to be deleted directly from the database (so callbacks will not be executed). :delete_all
导致直接从数据库中删除所有关联的对象(因此不会执行回调)。
:nullify
causes the foreign keys to be set to NULL. :nullify
导致外键设置为 NULL。 Callbacks are not executed.不执行回调。
:restrict_with_exception
causes an exception to be raised if there are any associated records.如果有任何关联的记录, :restrict_with_exception
会导致引发异常。
:restrict_with_error
causes an error to be added to the owner if there are any associated objects.如果有任何关联的对象, :restrict_with_error
会导致将错误添加到所有者。
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.如果与:through
选项一起使用,连接模型上的关联必须是belongs_to
,被删除的记录是连接记录,而不是关联记录。
:destroy
specified.是的,它将删除关联的建筑物作为依赖:destroy
指定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.