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

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now