5 Minute Code: Seeding Your Database with Faker

If you need to seed your database with dummy information you can use while you develop your app, you can do so easily with the Faker gem and a simple loop.  Faker automatically generates everything from unique email addresses to lorem ipsum paragraphs.  Here’s how:

1. Add the faker gem to your gemfile:

gem 'faker'

*Don’t forget to “bundle install”

2. In db/seeds.rb you’ll create the loop the will do the actual seeding.  First, make sure to require ‘faker’ at the top.  Next create a loop based on how many of the objects you want created.  Inside the loop, set each of the variables you want Faker to generate equal to the corresponding Faker attribute (i.e. email = Faker::Internet.email).  For a complete list of available fakers, make sure to check out the documentation.

3. Assuming you’ve already migrated your database, you can go ahead and seed using the rake db:seed command in the terminal.  Note: this will only work for attributes you’ve made attr_accessible in the model.

Here’s an example that will create 100 Users when seeded.  You’ll notice I hard coded the password and password_confirmation (’12345678′) instead of using Faker.  That’s a personal preference as having all of my fake users have the same password makes quickly signing in as one easier for me.


require 'faker'

100.times do
     email = Faker::Internet.email
     username = Faker::Name.name
     password = '12345678'
     password_confirmation = '12345678'
     city = Faker::Address.city
     company = Faker::Company.bs
     job_title = Faker::Name.title
     blerb = Faker::Lorem.paragraph(random_sentences_to_add = 5)
     personal_site = Faker::Internet.url

     User.create!( email: email , password: '12345678', password_confirmation: 
     '12345678', city: city, company: company, job_title: job_title, blerb: 
     blerb,  personal_site: personal_site)

And that’s how you fake it til you make it…

need to work on that one.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>