将 API 查询数据添加到 Rails 应用

Adding API query data to Rails app

我会尽我所能解释它。我对 RoR 很陌生。

我在 Rails 应用程序上有一个 Ruby,它只有一个 class 和一个我使用 scaffolding 创建的模型。控制器称为 countries_controller.rb 它具有以下代码:

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

模型country.rb为空:

class Country < ActiveRecord::Base
end

现在我使用 HTTParty 从 API 创建查询,我想将结果 :name 添加到 Rails 应用程序,这样每个 result/country 都会添加作为应用程序中的新行。将代码放在哪里,以及如何将 JSON 转换为数据库条目。我尝试了 JSON.parse(response) 但无法弄清楚。

这是我的查询:

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

我想我理解您的意思。当您使用 Web 服务时,您必须将其保存在数据库中,以便您的代码进入模型。

假设您有一个 countries table 和 name 字段。

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

然后在控制器中执行此操作

 def index
    @countries = Country.all
  end

它会给你所有国家的名字