I was working on a small Rails project and I needed some fake data to seed my DB. Normally, this would haven’t been a problem, but that time I needed profile pictures as well beside the first and last names. My first attempt was faker gem but couldn’t get the result I wanted, so looked around for another solution.
There is a great project, called randomuser.me. Using their API you can get random users with names, profile picutures, etc. You can find several Javascript tutorials how to use it. Now, I’m showing you how to benefit in a Rails project, when you seed random data.
To connect API you need to add seed.rb
rest-client
require 'rest-client'
Of course, to make it work you need to add
gem 'rest-client'
to Gemfile
.
To parse the response you need the json gem.
The rest is now very simple, you need to define the API endpoint and an array to store thre response. When you have the response, parse it and create DB entries.
require 'rest-client'
require 'json'
# API endpoint
url = 'https://randomuser.me/api/?results=12'
response = RestClient.get(url)
# array to store the response
results = JSON.parse(response.body)
results['results'].each { |result|
student = Student.create(
:first_name => result['name']['first'].capitalize,
:last_name => result['name']['last'].capitalize,
:photo_url => result['picture']['medium']
)
}
When you run the following command, Rails fetches the data, parse and seed it into your DB.
rails db:seed