In this tutorial, we are going to create a tiny rails application and explore several ways in which we can populate our database.
We will explore what Rails gives us out of the box as well as the Faker gem. If you would like to follow along and you do not Ruby on Rails installed please visit the InstallRails website, install Ruby on Rails and return to this page to follow along.
Lets say we want to build a writing application which we will name
journal. Our journal app is going to allow us to create a
title and enter some text in the
body of the journal. After creating the journal's
model we want to be able to add data to our database so that our client can play around and experiment with the app. We also want to give other developers who might be working on our app, the ability to quickly add data to our database when they clone our app.
$ rails new journal-1
$ rails generate scaffold Post title:string body:text
$ rails db:migrate
#config/routes.rb Rails.application.routes.draw do root 'posts#index' resources :posts end
$ rails console > Post.connection > Post.create(title: "First Journal", body: "Today I had fabulous day!")
#db/seeds.rb Post.create(title: "First Journal", body: "Today I had a fabulous day!")
Notice this is the same line of code we ran in our Rails console, only this time we have it saved in our seeds.rb file. This means we do not have to type it in again if we ever reset our database.
If you wanted to create several journal entries at once you could replace the above code with the following in your db/seeds.rb file.
#db/seeds.rb 10.times do |post| Post.create(title: "First Journal", body: "Today I had a fabulous day!") end
gem 'faker', '~> 1.8', '>= 1.8.4'
$ bundle install
#db/seeds.rb 10.times do title = Faker::Lorem.sentences(1) body = Faker::Lorem.paragraph(10) Post.create!(title: title, body: body) end puts "***************** Your seeds have been planted! ********************"
The code above is going to use Faker gem to create 10 posts (our journal entries) as soon as we seed our database as shown below.
First let us make sure that all our migrations are up by running the following line.
$ rails db:migrate:status
Status Migration ID Migration Name -------------------------------------------------- up 20171126150013 Create posts
$ rails db:migrate
$ rails db:seed
If you fire up your browser and visit 'localhost:3000' you should see 10 new entries were created on your landing page.
To clone this repository visit my Github page here