Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord:在自联接中删除子项后使外键无效_Ruby On Rails_Ruby_Activerecord_Self Join - Fatal编程技术网

Ruby on rails ActiveRecord:在自联接中删除子项后使外键无效

Ruby on rails ActiveRecord:在自联接中删除子项后使外键无效,ruby-on-rails,ruby,activerecord,self-join,Ruby On Rails,Ruby,Activerecord,Self Join,我的模型在ActiveRecord中有一个自连接,如下所示: class Employee < ActiveRecord::Base has_many :subordinates, class_name: "Employee", foreign_key: "manager_id" belongs_to :manager, class_name: "Employee" end class Employee

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

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

  belongs_to :manager, class_name: "Employee"
end 
class Employee

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

您想将
依赖::null化
添加到您的
有许多关联

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

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


如果只是创建表,则可以:

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}

哼对。OP就是这么问的。我不确定这就是我要找的。我是Ruby新手,所以我可能错了。但基本上,我有一个员工模型,具有自加入功能。我希望在删除相应的经理(也是employee表的一个实体)时,将employee的外键manager_id设置为null。你似乎建议的是一个不同的经理课程itself@NeelVasa哎呀!我的错。我错过了那部分。不过想法是一样的。将
dependent::nullify
添加到您的
has\u many:submitories
行中。我会更新代码。