如何将HTTParty响应保存到数据库?(更新!)

时间:2019-04-16 11:24:36

标签: ruby-on-rails ruby httparty

需要将httparty响应保存到db并在视图文件中调用

这是httrparty得到的

enter

在服务文件夹/

 class ParserService
      include HTTParty
      API_KEY = '882e10dd2b474a23bb7a3efa85e66b61'.freeze
      base_uri 'https://newsapi.org/v2/'
      default_params fielsd: "title, description, ulr, content"
      format :json

      def self.top_headlines(country_name='us') 
        new(country_name).top_headlines
      end

      def initialize(country_name='us')
        @options = { query: { country: country_name, apiKey: API_KEY} }
      end

        def top_headlines 
          response = self.class.get("/top-headlines", @options)
          pars_json = response.parsed_response
          pars_json["articles"].each do |k|
            @source = ActiveModel::Source.create(google_id: k["id"], name: k["name"])

            @article = Article.create(title: k["title"], source_id: @source.id,
                                      description: k["description"], content: k["content"])

          end
        end  
    end

ArticleController

class ArticlesController < ApplicationController


    def index
        @articles = Article.all
    end
end

和型号

class Article < ApplicationRecord
    belongs_to :source, class_name: "Source", optional: true
    validates :title, presence: true
    validates :source_id, uniqueness: true 

end

和schema.rb

enter image description here

我现在所做的 如果尝试在(rails c)控制台中保存Article时出现此错误,请确认

enter image description here

当尝试评论验证时,它会保存,但是.....会保存空字段

enter image description here

我真的不明白为什么它会空,当我直接调用JSOn而不保存到db时,在视图上显示了我需要的所有内容,但是现在我有了这个... 在索引页面上

enter image description here

enter image description here

然后在控制台中出现错误

enter image description here

我可以想象如何解决此问题以及哪里出错了

1 个答案:

答案 0 :(得分:2)

从我的表情来看:

pars_json.each do |k|
  art = ParserService.new('us')
  res = response.body
  art.title = res["title"]
  art.save
end

这是您要将其保存到数据库的地方吗?我不认为ParserService是您创建的能够反映数据库中表的模型。

如果您要使用Article模型来保存从API调用中解析的每个对象,则需要执行类似上述操作:

pars_json.each do |k|
  article = Article.create(title: k["title"], k["description"]...)
end

尝试首先打印出确切的k,然后对齐对象键以对应正确的Article字段。

同样,要保存到数据库,您需要使用创建的模型来反映数据库中的表。如果您的数据库上有articles表,您想在其中保存API响应数据,那么您应该创建Article的实例并将其保存。

然后在控制器中,它只是通过@articles = Article.all或您希望运行以获取文章列表的任何查询来调用它。

我建议在后台作业中运行ParserService,以使API在并行进程中提取数据,而又不会影响到Rails进程过多