Rails: violates foreign key constraint

廉价感情. 提交于 2019-11-30 03:01:49

问题


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

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

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".

In my seed.rb

Book.destroy_all
Genre.destroy_all
...create data 

回答1:


Add dependent: :destroy option to your has_many definitions.

Check docs

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
)



回答2:


Try this:

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


来源:https://stackoverflow.com/questions/31826409/rails-violates-foreign-key-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!