Subscribe to The Rails Future        RSS Feed
-----

Rails: Populate your database with sample data

Icon Leave Comment
Your rails app has a special folder where you put "tasks" to be run. This folder is...
lib/tasks/



Most people have a task that they use to populate their database with "test data". This powerful feat can be accomplished with the simple command...
$  rake db:populate



But for it to work, you of course need to first define the task "db:populate". Here's a sample definition you're free to look over.


(lib/tasks/sample_data.rake)
namespace :db do
  desc "Fill database with sample data"
  task :populate => :environment do
    Rake::Task['db:reset'].invoke
    make_users
  end
end


def make_users
  admin = User.create!(:email => "[email protected]",
                       :password => "password",
                       :password_confirmation => "password")
  admin.toggle!(:admin)
  
  admin.persons.create(:first_name => "Firstname", :last_name => "LastName", :email => admin.email)
  

  
  99.times do |n|
    name = Faker::Name.name
    email = "example-#{n+1}@railstutorial.org"
    password = "password"
    User.create!(:email => email,
                 :password => password,
                 :password_confirmation => password).persons.create(:first_name => name, :last_name => name, :email => email)
   
    
  end
end




In that task, we first create an admin user, then we make 99 other users. It's very handy for testing with... As your application undergoes changes, you'll likely be watching this file closely and keeping it up to date as you're testing new functionality.

Never Forget
$  rake db:populate

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Tags

    Search My Blog

    3 user(s) viewing

    3 Guests
    0 member(s)
    0 anonymous member(s)

    Categories