我在ActiveRecord中为我的模型进行了自我加入,如下所示:
class Employee < ActiveRecord::Base
has_many :subordinates, class_name: "Employee",
foreign_key: "manager_id"
belongs_to :manager, class_name: "Employee"
end
如果我删除了Manager行,我希望将该Manager下所有员工的'manager_id'外键值设置为NULL。这是ActiveRecord隐式处理的东西,还是需要在某处定义的东西。
答案 0 :(得分:6)
您想将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
答案 1 :(得分:2)
理想情况下,您应该在数据库中设置触发器,而不是依赖Active Record来执行更新。
如果您只是创建表格,您可以:
create_table :employees do |t|
t.references :manager, foreign_key: {to_table: :employees, on_delete: :nullify}
# ...
end
或者,如果表已经存在且您只是添加引用:
add_reference :employees,
:manager,
foreign_key: {to_table: :employees, on_delete: :nullify}