Ruby on rails Rails外键冲突删除与依赖销毁有很多关系

Ruby on rails Rails外键冲突删除与依赖销毁有很多关系,ruby-on-rails,postgresql,activerecord,postgresql-9.5,Ruby On Rails,Postgresql,Activerecord,Postgresql 9.5,在Rails 4.2模型中,我有一个简单的和许多关系: class Owner < ActiveRecord::Base has_many :nested_things, :inverse_of => :owner, :class_name => "Nested::Thing", :dependent => :destroy end class Nested::Thing < ActiveRecord::Base belongs_to :owner, :i

在Rails 4.2模型中,我有一个简单的
和许多
关系:

class Owner < ActiveRecord::Base
  has_many :nested_things, :inverse_of => :owner, :class_name => "Nested::Thing", :dependent => :destroy
end

class Nested::Thing < ActiveRecord::Base
  belongs_to :owner, :inverse_of=>:nested_things
end
所有者
被删除时,这是一个耗时的过程-在本地,这个特定的记录生成了一个109000行的日志文件,其中包含所有执行的SQL。但是,嵌套的\u-things关系会导致整个操作中止,因为外键检查失败

以下是日志文件的相关部分:

> grep -n nested_things delete-owner.txt 

....

109762: SQL (1.1ms)  DELETE FROM "nested_things" WHERE "nested_things"."id" = $1  [["id", 8665]]

109836: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: 
        ERROR:  update or delete on table "owners" violates foreign key 
        constraint "nested_things_owner_id_fk" on table "nested_things"

109837: DETAIL:  Key (id)=(6343) is still referenced from table "nested_things".

此所有者只有一个嵌套项什么会导致:dependent=>:在Rails中销毁关系,以删除依赖关系,但外键检查失败?

结果表明,答案是Rails上的一个默认作用域,有许多关系在销毁过程中未被考虑。

我认为索引可能已损坏,但是重新索引并没有改变任何东西。这不是我尝试直接从表中删除时检查的第一个外键。删除另一个也包含嵌套内容的所有者记录效果很好。您是如何消除它的?您是删除了默认\u作用域,还是用另一种方法解决了它?看起来我在发生外键冲突的模型中添加了一个before\u destroy,删除了默认作用域中不存在的对象。默认作用域是
enabled:true
,因此我的before\u destroy删除了所有启用了false的内容,或者启用了nil:
before\u destroy{NestedThings.unscoped.where(:owner\u id=>self.id,:enabled=>[nil,false])。destroy\u all}
> grep -n nested_things delete-owner.txt 

....

109762: SQL (1.1ms)  DELETE FROM "nested_things" WHERE "nested_things"."id" = $1  [["id", 8665]]

109836: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: 
        ERROR:  update or delete on table "owners" violates foreign key 
        constraint "nested_things_owner_id_fk" on table "nested_things"

109837: DETAIL:  Key (id)=(6343) is still referenced from table "nested_things".