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: "example@railstutorial.org",
                 password: "foobar",
                 password_confirmation: "foobar")
    99.times do |n|
      name  = Faker::Name.name
      email = "example-#{n+1}@railstutorial.org"
      password  = "password"
      User.create!(name: name,
                   email: email,
                   password: password,
                   password_confirmation: password)
    end
  end
end

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.

ref: http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#sec-sample_users

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s