Rails外键违规删除has_many与依赖destroy的关系

时间:2016-09-13 19:38:58

标签: ruby-on-rails postgresql activerecord postgresql-9.5

我在Rails 4.2模型中有一个简单的has_many关系:

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

模型比这复杂得多,还有许多其他关系。

当有人今天尝试删除Owner时,它失败了,因为nested_things表上有一个外键:

> psql annoying_problem

psql (9.5.3)
Type "help" for help.

annoying_problem=# \d+ nested_things
                                                            Table "public.nested_things"
      Column      |            Type             |                           Modifiers                            | Storage  | Stats target | Description 
------------------+-----------------------------+----------------------------------------------------------------+----------+--------------+-------------
 id               | integer                     | not null default nextval('nested_things_id_seq'::regclass)     | plain    |              | 
 owner_id         | integer                     |                                                                | plain    |              | 

 Indexes:
    "nested_things_pkey" PRIMARY KEY, btree (id)
    "ix_nested_things_on_owner_id" btree (owner_id)
Foreign-key constraints:
    "nested_things_owner_id_fk" FOREIGN KEY (owner_id) REFERENCES owners(id)

删除owner时,这是一个耗时的过程 - 本地此特定记录生成了所有已执行SQL的109,000行日志文件。但是, nested_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".

此所有者只有一个nested_things条目。 什么可能导致a:dependent =&gt; :破坏Rails中的关系,删除依赖关系,但是无法检查外键吗?

1 个答案:

答案 0 :(得分:1)

原来答案是has_many关系的默认范围,在销毁中没有考虑到。