Create Sample Data

Add faker gem in your Gemfile:

  gem 'faker', '1.1.2'

then install as usual:

  $ bundle install

Create a rake file for rake task in lib/tasks directory.e.g: lib/tasks/sample_data.rake

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    User.create!(name: "Example User",
                 email: "",
                 password: "foobar",
                 password_confirmation: "foobar")
    99.times do |n|
      name  =
      email = "example-#{n+1}"
      password  = "password"
      User.create!(name: name,
                   email: email,
                   password: password,
                   password_confirmation: password)

Now run the rake task using following command:

  rake db:populate

In the above command “db” is namespace and “pupolate” task name.
After running the rake task there will be 100 users in db.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s