且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Rails 中销毁之前检查所有关联

更新时间:2021-12-31 04:03:39

你可以通过 :dependent =>has_many 调用的 :restrict 选项:

You can pass the :dependent => :restrict option to your has_many calls:

has_many :models, :dependent => :restrict

这样,只有在没有其他关联对象引用它的情况下,您才能销毁该对象.

This way, you will only be able to destroy the object if no other associated objects reference it.

其他选项是:

  • :destroy - 销毁所有调用其 destroy 方法的关联对象.
  • :delete_all - 删除所有关联对象调用它们的 destroy 方法.
  • :nullify - 将关联对象的外键设置为 NULL 无需调用它们的保存回调.
  • :destroy - destroys every associated object calling their destroy method.
  • :delete_all - deletes every associated object without calling their destroy method.
  • :nullify - sets the foreign keys of the associated objects to NULL without calling their save callbacks.