Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: violates foreign key constraint

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 
like image 776
Coda Chang Avatar asked Aug 05 '15 07:08

Coda Chang


2 Answers

Try this:

ActiveRecord::Base.connection.disable_referential_integrity do
    Book.destroy_all
    Genre.destroy_all
    # ...create data 
end
like image 119
scorix Avatar answered Nov 13 '22 16:11

scorix


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
)
like image 42
Andrey Deineko Avatar answered Nov 13 '22 16:11

Andrey Deineko