Chris Mendez in For Developers, Ruby

Rails: Populating Your Database using Seeds.rb

When I'm building a new app, I prefer to populate my site with fake data so that I can see how the app actually starts responding to queries. There are a few examples of how I populate my rails app with development data.

LOREM IPSUM

The Easy Way

Step 1 - Add Populator or Faker to your Gemfile

# Execute: rails db:populate
# https://github.com/ryanb/populator
gem 'populator'

# https://github.com/stympy/faker
gem 'faker'  

Step 2 - Load fake data within db/seeds.rb

require 'faker'  
require 'populator'

# Create 10 users with fake data
User.populate(10) do |u|  
  u.fname           = Faker::Name.first_name
  u.lname           = Faker::Name.last_name
  u.full_name       = u.fname + " " + u.lname
  u.screen_name     = Faker::Internet.user_name
  u.password_digest = Faker::Internet.password(4, 20)
  u.auth_token      = Faker::Internet.password(10, 20, true, true)
  u.description     = Faker::Lorem.paragraph(2)
end  

Source: Railscast

Import JSON from Github

This example shows you how to pull JSON data from an online source, parse it, convert it into ruby objects and publish it to your local database.

First let's create a model. For this example, I'm creating a Publication model with three attributes, title, description, file_url.

rails g model Publication title:string, description:text, file_url:string  

Next, place this inside of db/seeds.rb. This script will open an URI request to a JSON file on Github, parse the file by reading each_line and creating new instances of Publication.

require 'open-uri'  
require 'json'

Publication.delete_all

open("https://raw.githubusercontent.com/chrisjmendez/ror-subscriptions/master/db/seed_data/publications.json") do |publications|  
  data = []
  publications.read.each_line do |publication|
    @item = JSON.parse(publication)
      object = {
            "title":        @item["title"],
            "description":  @item["description"],
            "file_url":     @item["file_url"]
      }
      data << object
  end
  Publication.create!(data)
end  

My Code Example


Resources