【发布时间】:2019-04-16 11:24:36
【问题描述】:
需要将httparty响应保存到db并在视图文件中调用
这就是 httrparty 得到的东西
在服务文件夹中/
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
文章控制器
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
这就是我现在所做的 如果尝试在 (rails c) 控制台中保存文章出现此错误,请验证
当尝试评论验证时,它保存但....它保存空字段
我真的不明白为什么它是空的,当我直接调用 JSOn 而不保存到数据库时,它显示了我需要的所有内容,但现在我有了这个...... 在索引页上
后来在控制台出现错误
我可以想象如何解决这个问题以及哪里出了问题
【问题讨论】:
-
你能告诉我们你卡在哪里了吗:)
-
@Manoj 文章现在显示在页面上,但每次刷新页面时它都会调用 API 方法,我想将其保存到数据库并从数据库调用它。坚持保存到数据库
标签: ruby-on-rails ruby httparty