Ruby/Sinatra and Organizing Your Seed FileS!
3 min read
It starts with a messy Seed.rb
We've all been there. You're working on a project and setting up your new database with some information. Whether the information is real or fake, eventually your seed file starts getting clunky and it becomes difficult to locate information in different areas as you pass around 200 lines of data.
Does your seed.rb file look like this and have data you can't even find?
We can fix that.
In this example, I'm working with a database that has the following tables:
I'm not going to go into detail here about that but you can probably imagine a database with five (5) tables like the ones I listed above and how easily you can begin to have a large amount of information being stored in it. For the purposes of my project, the table layout above looked like this visually:
As you can see, Students are part of a course and Students can have questions. Questions belong to their respective Assignments, which belong to Modules, which belong to Courses.
This is a lot of seed data to have, especially if you want to have a database which, at minimum, contains Course + Module + Assignment information - even without any questions or students.
In my case, a single course has about ten (10) modules and within those ten modules are approximately sixty (60) assignments.
How can we organize that seed file so it's easily to update?
Well.. You need to split it up.
Object Oriented Seeding?
I wanted to have a way I could split my seed file into multiple other files. Following the standard convention of having appropriately named subdirectories, I began by creating the folder '/db/seeds'.
Next, I created new Ruby files for every area I wanted to seed. I split this up by the table each seed would supply data for.
Once this is finished, you can add your seed data to the appropriate files. For example, my file '02_course_seed.rb' contains this data:
How do we make these files functional, though? You need this to all work properly with commands like bundle exec rake db:seed.
The answer is that you will still have your original 'seeds.rb' file within the '/db' directory. We just need to add one small command to make it all work seamlessly.
Making use of the Ruby class Dir, we can tell Ruby to find every single file within the subfolder 'seeds' that has an 'rb' extension, sort them, and load each file as a seed file one at a time.
Now, run bundle exec rake db:seed and you'll find each file performed exactly like you needed to have some nicely new organized seed files!
Thanks for reading this! I hope this helps you organize your large seed files better! If you enjoyed the content, please check back and also follow my journey on Twitter!