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
Try this:
ActiveRecord::Base.connection.disable_referential_integrity do
Book.destroy_all
Genre.destroy_all
# ...create data
end
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With