Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specify execution order of seed files in rails

I am trying to add data to two tables courses and course_subjects tables with the predefined data(as I don't need to alter these tables content). course_subjects table refers to courses table for the column course_id .When executing the rake db:seed command following error occurs.

ActiveRecord::InvalidForeignKey: Mysql2::Error: Cannot add or update a child row: a foreign key constraint fails 

How can I specify to execute course.rb in seed first then course_subjects. I have data in separate csv files

like image 693
CR7 Avatar asked Jan 30 '17 12:01

CR7


1 Answers

How I do it is by making another folder under db called seeds and storing my files in there. This lets me separate out the seed data so its not to clumped together.

In the seeds.rb file I then place this load command and then run db:seed

load 'db/seeds/users.rb'
load 'db/seeds/couples.rb'
load 'db/seeds/user_couples.rb'

So in each folder I would recommend loading in the corresponding csv and uploading the data. Then for the tables that you need a foreign key to you should load those later and use rails to load the data objects you need in.

If you are still looking for an example of it you can see it in this project.

like image 51
Tall Paul Avatar answered Oct 12 '22 14:10

Tall Paul