Ruby’s Faker Gem
Makes the process of creating multiple seed data easier and fun…
- What is ‘faker’
Faker is one of many ruby gems, which focuses on generating dummy seed data developers use to test written codes. Using faker is pretty simple and does not require a ton line of codes.
- Installing ‘faker’
To install ‘faker’, we need to define the gem inside our application gemfile by writing gem ‘faker’ , or running in your terminal ‘gem install faker’.
Once installed , it needs to be required in the ‘seeds.rb’ file located inside of the database folder ‘db’, before writing any line of code.
All steps after this are assuming the tables have already been created and that we ran the migrations already.
- A little explanation about the above code
In line 1 of the picture above we’re requiring the faker gem.
Line 2 and 3 are necessary for when reseeding the database. They help keep the number of seed generated the same, by destroying the first generated seeds, and creating some new ones.
Line 6 to 12 will handle the creation of our seed data using the ‘faker’ gem syntax. (see https://github.com/faker-ruby/faker for faker documentation)
After writing our code inside of the ‘seeds.rb’ file, we run ‘rake db:seed’ in our terminal to actually seed the database.
For the above code, running the command for the first time will generate a hundred random instances of dishes for our dishes table, with id:integer starting at 1 and incrementing to 100.
Each instance of a dish will have a name randomly assigned, and might contain some duplicates, a price within the range of $0 (highly doubt the possibility of that in real life) and $15., and also restaurants ids from 1 through 10 in the foreign keys column. We will eventually need to generate some instances of the restaurants table. To be exact, ten, for our above code. The process is very similar.
- A little tip when generating data with ‘faker’
A nice tips would be to write all the seed data at once before seeding the table for the first time. As mentioned above, using the ‘table_name.destroy_all’, in our case ‘Dishes’, will destroy the instances, and create a new set when we reseed. Depending on the associations between our tables, adding new seed data and reseeding might cause a mismatch of ids.
If for some reason you encounter some id mismatch issues, make sure the data are properly written, and once done, run ‘rake db:reset’ in the terminal. this we drop the database, rerun the migrations, and reseed the database. And no additional gem is required for this step.
- Read about ‘faker’ documentation