Rails:违反外键约束

我有三种模式: BookgenreBookGenre ,这里有关系:

 class BookGenre < ActiveRecord::Base belongs_to :book belongs_to :genre end class Book < ActiveRecord::Base has_many :book_genres has_many :genres, through: :book_genres end class Genre < ActiveRecord::Base has_many :book_genres has_many :books, through: :book_genres end 

然后我使用seed文件将数据放入这些表中。

但是当我想再次使用rake db:seed时,它显示了这个错误

 ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "books" violates foreign key constraint "fk_rails_4a117802d7" on table "book_genres" DETAIL: Key (id)=(10) is still referenced from table "book_genres". 

在我的seed.rb

 Book.destroy_all Genre.destroy_all ...create data 

为您的has_many定义添加dependent: :destroy选项。

检查文档

然而,更好的选择是尊重数据完整性是在数据库级别设置CASCADE DELETE

试试这个:

 ActiveRecord::Base.connection.disable_referential_integrity do Book.destroy_all Genre.destroy_all # ...create data end