How to seed a Rails app with an external API

Bhavani
3 min readJun 4, 2021

If your Rails app has a “has_many” relationship, and you’re looking to seed both the parent and the child from an external API, you’ve come to the right place.

I created an Animal Crossing rails app where users can keep track of materials required for Diys. Diys have many materials, and multiple materials were nested in the Diy array under materials.

Installation:

I installed the gems ‘rest-client’, for the external API request, and ‘dotenv-rails’ to keep my API key protected (you will need to request a key if your API has one).

Protecting the API Key:

Once you run ‘bundle install’, you can create a .env file that will keep your API key hidden.

Seeding the data:

I chose to seed my data within the Diy.rb model within a method. You must establish your has_many and belongs_to in your models, as well as an accepts_nested_attributes_for in order to create the child model at the same time.

I know it looks like a lot is going on, but i’ll explain it line by line.

  1. self.get_data
  • The value of self is the same as saying Diy.get_data, because we are in the Diy.rb model, and therefore in the Diy class
  • get_data is the method I will later call in my seeds file to seed the data.

2. resp =

  • This is saving all of the data i receive from the API. The next few lines are my API call, including the key with it’s associated header

3. diy_data

  • This is a variable that saves our response, parsed into JSON, and only including the body portion of our array. (You can use postman or a binding.pry to see what your response will look like)

4. Iterating over each diy

  • I created a variable that saves each diy as a hash, and also contains a materials_attributes section (you have to name this “child_model_name(s)_attributes”), and this takes in the array of materials, which is a hash of each material with two keys of name, and count. My material table included matching name and count keys, as well as a Diy_id key so that everything would nest nicely.

5. Creating the Diy with params variable

  • Since this variable already has what I need to create a Diy as well as its associated materials, I just had to call .create! on Diy, with the params starting at the diy: key.

The final step, going back to the seeds file:

To ensure there are no duplicates every time I run rails db:seed, I added a .destroy_all for each of the classes. You have to destroy your child model first, before you destroy the parent, otherwise you will get an error for orphaned models. Then you simply call the Diy.get_data method defined in the model class, and run rails db:seed. If you go into the rails console and call Diy.first.materials, you should see all of your materials associated with your Diy.

--

--