Skip to content

Backend Training: Seed Data

Nelson Lee edited this page Nov 29, 2017 · 6 revisions

🔖 : Seeding Database, faker

To seed the database we will use faker gem to populate fake data. From the starter template, we have a custom seed task inside lib/task/seed.rake that automatically gets all the files inside db/seeds/ and generate a task for it.

Create seeds for Faq

# db/seeds/faqs.rb
Faq.delete_all

10.times do
  Faq.create(
    question: Faker::Lorem.sentence(1),
    answer: Faker::Lorem.paragraph(3)
  )
end

Let's run it..

$ rake db:seed:faqs

Let's check to see if they are generated

$ rails c
irb(main):003:0> Faq.count
   (0.4ms)  SELECT COUNT(*) FROM "faqs"
=> 10

Great we generated 10 fake FAQs as expected.

Create seeds for Post

# db/seeds/post.rb
Post.delete_all

20.times do
  Post.create(
    title: Faker::Lorem.sentence(1),
    content: Faker::Lorem.paragraph(20),
    published: true
  )
end

Let's run it..

$ rake db:seed:posts

Let's check to see if they are generated

$ rails c
irb(main):001:0> Post.count
   (0.7ms)  SELECT COUNT(*) FROM "posts"
=> 20

Great we generated 20 fake Posts as expected. Let's commit and move on..

$ git add -A
$ git commit -m 'Post and Faq seeds'

↪️ Next Section: Collection Rendering