Reputation: 649
So I wanted to seed some data in my rails API form a CSV file. So, I did the needful:
seed.rb
require 'CSV'
Meal.destroy_all
Vendor.destroy_all
CSV.foreach(Rails.root.join('./db/vendordata.csv'), headers: false) do |r|
Vendor.create! do |m|
m.vendorname = r[0]
m.email = r[1]
m.phone_number = r[2]
m.company_name = r[3]
m.company_branch = r[4]
m.password = r[5]
end
end
CSV.foreach(Rails.root.join('./db/meals.csv'), headers: false) do |r|
Meal.create! do |m|
m.vendor_id = r[0]
m.name = r[1]
m.desc = r[2]
m.price = r[3]
m.sample_alt = r[4]
m.discount = r[5]
m.class = r[6]
end
end
However, when I first ran rails db:seed
, I got an SQLite3::ConstraintException: FOREIGN KEY constraint failed
error, which would have had to come from Meals
... cause that has a vendor_id
. I went and corrected the error in my CSV file, ran rails db:seed
and still got the same error. Now I have emptied my seed.rb
, and I still get that same error.
What I have tried:
I have run Rails.cache.clear
in my console.
I reset my database.
Upvotes: 0
Views: 199
Reputation: 1585
This likely has to do with your database randomly generated vendor_id.
Even though you are cleaning the database, the vendor_id internal counter doesn't reset (I'm assuming it's an auto-increment integer).
So if you had a Meal with vendor_id = 3 for example, after deleting the data and seeding again, the vendor_ids would start with, for example, 4, and your Meal model would reference non-existent ids. That's why you get a foreign key failure.
Try actually destroying your entire database and building again, instead of just deleting the data.
Alternatively, as pointed out, you can run ActiveRecord::Base.connection.execute('ALTER TABLE foo_bars AUTO_INCREMENT = 1')
to reset the auto_increment.
Upvotes: 4