Rails: 违反外键约束

Rails: violates foreign key constraint

我有三个模型: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 

试试这个:

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

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

Check docs

尊重数据完整性的更好选择是在数据库级别设置 CASCADE DELETE:例如,您有 comments table 和 users table.用户有很多评论你想添加一个 foreign_key 到 table comments 并设置在用户被销毁时删除评论你可以使用以下内容(on_delete: :cascade 选项将确保它):

add_foreign_key(
  :comments,
  :users,
  column:
  :user_id,
  on_delete: :cascade
)