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
  end
end

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
end

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'
end

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

Reference

Faker Gem


Related Articles


Create your own user feedback survey