Rails:违反外键约束 [英] Rails: violates foreign key constraint
问题描述
我有三个模型:Book
,genre
,BookGenre
,这是一些关系:
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屋!