ActiveRecord:在自连接中删除子项后使外键无效

ActiveRecord: Nullify foreign key after deleting a child in self-joins

我的模型在ActiveRecord中有一个自连接,如下:

class Employee < ActiveRecord::Base
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"

  belongs_to :manager, class_name: "Employee"
end 

如果我删除经理行,我希望该经理下的所有员工的 'manager_id' 外键值设置为 NULL。这是由 ActiveRecord 隐式处理的东西,还是需要在某处定义的东西。

您想将 dependent: :nullify 添加到您的 has_many 协会。

class Employee…
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id",
                          dependent: :nullify
end

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

理想情况下,您应该在数据库中设置触发器,而不是依赖 Active Record 来执行更新。


如果您只是创建 table,您可以:

create_table :employees do |t|
  t.references :manager, foreign_key: {to_table: :employees, on_delete: :nullify}
  # ...
end

或者,如果 table 已经存在而您只是添加引用:

add_reference :employees,
              :manager,
              foreign_key: {to_table: :employees, on_delete: :nullify}