Search code examples
ruby-on-railsrubyscaffolding

Adding API query data to Rails app


I'll try to explain it the best way I can. I'm very new to RoR.

I have a Ruby on Rails app, it has only one class and one model that I created using scaffolding. The controller is called countries_controller.rb it has the following code:

class CountriesController < ApplicationController
  before_action :set_country, only: [:show, :edit, :update, :destroy]

  def index
    @countries = Country.all
  end

  def show
  end

  private

    def set_country
      @country = Country.find(params[:id])
    end

    def country_params
      params.require(:country).permit(:name)
    end

end

The model country.rb is empty:

class Country < ActiveRecord::Base
end

Now I created query from an API using HTTParty, and I want to add the results :name to the Rails app, so that each result/country will add as a new row in the app. Where to put the code, and how to turn JSON to db entries. I tried JSON.parse(response) but couldn't figure it out.

This is my query:

require 'httparty'

response = HTTParty.get('http://api.population.io/1.0/countries/?format=json', format: :json)

countries = response["countries"]

countries.each do |c|
  puts c

end


Solution

  • I think I understand your point .When you are consuming web service you have to save that in Database so your code will go in model.

    Let suppose you have a countries table with a name field.

    class Country < ActiveRecord::Base
        require 'httparty'
    
        response = HTTParty.get('http://api.population.io/1.0/countries/?format=json', format: :json)
    
        countries = response["countries"]
    
        countries.each_with_index do |country|
          country = self.find_by(name: country[i])
            if country == nil
              self.create!(name: country[i])
            end
        end
    end
    

    Then in controller when you do this

     def index
        @countries = Country.all
      end
    

    It will give you all the countries name