Populating a Database in Rails 5

In this article, we will the changes required to get the railscast episode on Populating a Database to work with Rails 5. Create the models.

rails g model category name
rails g model person name company phone country state city zip street email
rails g model product name price:decimal category:references description:text 

Migrate the database. Add the faker and populator gems to Gemfile.

gem 'faker'
gem 'populator'

Run bundle. Here is the seeds.rb:

[Category, Product, Person].each(&:delete_all)

Category.populate 20 do |category|
  category.name = Populator.words(1..3).titleize
  Product.populate 10..20 do |product|
    product.category_id = category.id
    product.name = Populator.words(1..5).titleize
    product.description = Populator.sentences(1..2)
    product.price = [4.99, 19.95, 100]
    product.created_at = 2.years.ago..Time.now

Person.populate 100 do |person|
  person.name    = Faker::Name.name
  person.company = Faker::Company.name
  person.email   = Faker::Internet.email
  person.phone   = Faker::PhoneNumber.phone_number
  person.street  = Faker::Address.street_address
  person.city    = Faker::Address.city
  person.state   = Faker::Address.state_abbr
  person.zip     = Faker::Address.zip_code

Populate the database.

rails db:seed

Generate the controllers.

rails g controller categories index show new create edit update destroy
rails g controller products index show new create edit update destroy
rails g controller people index

Form tag should have:

<%= instead of <%.

Controllers should use strong parameters. Here is the routes.

Rails.application.routes.draw do
  resources :categories, :products, :people

  root 'products#index'

You can download the source code for this article from https://github.com/bparanj/meg.


Faker Gem

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.