我有三个模型:Book
, genre
, BookGenre
,以下是关系:
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".
In my seed.rb
Book.destroy_all
Genre.destroy_all
...create data
Add dependent: :destroy
选项给你的has_many
定义。
检查文档
然而,尊重数据完整性的更好选择是设置CASCADE DELETE
在数据库级别:比如说,你有comments
表和users
桌子。用户有很多评论您想向表添加外键comments
并设置在用户被销毁时删除评论,您将使用以下内容(on_delete: :cascade
选项将确保它):
add_foreign_key(
:comments,
:users,
column:
:user_id,
on_delete: :cascade
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)