Skip to content

Instantly share code, notes, and snippets.

@thejourneydude
Last active December 14, 2015 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejourneydude/02f8831e640aa3270a9b to your computer and use it in GitHub Desktop.
Save thejourneydude/02f8831e640aa3270a9b to your computer and use it in GitHub Desktop.
I recently had to populate/seed a database for a project of mine. This was crucial for several reasons. First, we wouldn’t have to go inside console and create our own data. Second, we have an easier time testing models. Third, when working with various features (such as RailsAdmin) we have a sense of what the final product will look like.
In this case, I decided to create a rake task titled db:populate. First I reset the database. Then I ran simple loops creating records after records of models. One big question is how do you create unique entries? For example, if I created 100 users I want each one to have a different name.
This is where Faker comes in. With Faker, I can simply call a method provided by the gem that will randomly select a name from their array. For example,
Faker::Name.first_name
will return a random first name.
Faker::Internet.email
will return a random email address.
Faker::Address.state
will return a random US state.
There is plenty more methods to choose from, you can get company names, lorem paragraphs, and much more. If you want to find out more about what a rake task looks like using Faker, check out the code below.
require 'faker'
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
# This line below is commented out because Heroku sucks
Rake::Task['db:reset'].invoke
10.times do
user = User.new
user.name = Faker::Name.name
user.save
end
end
end
For more info on Faker,
https://github.com/stympy/faker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment