Rails:违反外键约束 [英] Rails: violates foreign key constraint

查看:99
本文介绍了Rails:违反外键约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型:BookgenreBookGenre,这是一些关系:

I have three models: Book, genre, BookGenre, and here are relationships:

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文件将数据放入这些表中.

And then I use seed file to put data into these tables.

但是当我想再次执行rake db:seed时,它显示了此错误

But when I want to do rake db:seed again, it showed this error

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:例如,您有comments表和users表.用户有很多注释您想向表comments中添加一个foreign_key并设置为在用户被销毁时删除该注释,您可以使用以下命令(on_delete: :cascade选项将确保它):

Yet better option to respect data integrity is to set the CASCADE DELETE on the database level: say, you have comments table and users table. User has many comments You want to add a foreign_key to table comments and set deleting the comment whenever the user is destroyed you would go with the following (the on_delete: :cascade option will ensure it):

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

这篇关于Rails:违反外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆