ga-wdi-exercises / project2

[project]
1 stars 30 forks source link

Error with rails db:seed #862

Closed twelve13 closed 7 years ago

twelve13 commented 7 years ago

I get this error when trying to seed my database:

ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "boards" violates foreign key constraint "fk_rails_de121e0ff9" on table "listings" DETAIL: Key (id)=(1) is still referenced from table "listings". : DELETE FROM "boards" WHERE "boards"."id" = $1

Here are my migrations:

class CreateBoards < ActiveRecord::Migration[5.0] def change create_table :boards do |t| t.string :title t.string :image end end end

class CreatePosts < ActiveRecord::Migration[5.0] def change create_table :posts do |t| t.string :title t.string :image t.string :url end end end

class CreateListings < ActiveRecord::Migration[5.0] def change create_table :listings do |t| t.references :board, index: true, foreign_key: true, null: false t.references :post, index: true, foreign_key: true, null: false end end end

Can you point me in the right direction? Thanks!

juancgarcia commented 7 years ago

I think this has to do with the destroy order in your seeds file. You're trying to destroy a parent object while a child still points to it via foreign key. In this case I think the boards are being destroyed but there are still listings pointing to them.

You can fix this either by adding dependent: :destroy to your has_many relationship in the Board class and/or flip your destroy_all lines so that listings are destroyed first.

twelve13 commented 7 years ago

I moved the Listing.destroy_all to the top and that fixed it! Thanks!!