【发布时间】:2017-09-08 00:05:13
【问题描述】:
Rails 4.5 Ruby 2.3.1
我从 API 获取 json 并尝试将以下内容存储到模型 CLrates 1.时间戳为unix时间(日期) 2. Currency_code(字符串) 3. 报价(十进制货币价值)
我可以在解析 json 后在 irb 中使用以下内容,并且知道如何使用:response["quotes"] 单独获取元素。当body如下时,如何生成要保存在上述模型中的参数:
irb(main):036:0> puts response.body
{
"success":true,
"terms":"https:\/\/xxxxx.com\/terms",
"privacy":"https:\/\/xxxxx.com\/privacy",
"timestamp":1504817289,
"source":"USD",
"quotes":{
"USDAED":3.672703,
"USDAFN":68.360001,
"USDCUC":1,
"USDCUP":26.5,
"USDCVE":91.699997,
"USDCZK":21.718701,
............ many more lines removed for brevity
"USDZWL":322.355011
}
我可以使用单独的关联模型来做到这一点,但对如何创建参数以保存到单个表中几乎一无所知。
如果您需要有关 httparty GET(客户端)的信息,以下链接让我明白了这一点,非常值得一读: 1.http://www.rubydoc.info/github/jnunemaker/httparty/HTTParty/ 2.http://eric-price.net/blog/rails-api-wrapper/ 3.https://www.driftingruby.com/episodes/playing-with-json
lib/claer.rb 中的类和方法:
class clayer
include HTTParty
format :json
read_timeout 10
def self.get_quotes
response = HTTParty.get('http://www.nnnnnnn.net/api/live?
access_key=nnnnnnnnnn&format=1')
end
end
我使用了 irb,因为我还在学习如何通过 rails c 运行它。这将在控制器中调用并保存,但是需要弄清楚如何从 json 中获取参数
感谢您的帮助
好的:挖掘后我认为我在正确的轨道上 我得到响应[“QUOTES”],遍历它们并构建所需的参数,在循环结束时保存每个参数
rates = response["QUOTES"]
rates.each do |k,v|
clrate = Realtimerates.new
clrate.date = response["timestamp"]
clrate.countrycode = "#{k}"
clrate.price = "#{v}"
clrate.save
end
试一试
在模型中
class Realtimerate < ActiveRecord::Base
include HTTParty
format :json
read_timeout 5
def self.get_cl_rates
response = HTTParty.get('http://www.mmmmm.net/api/live?access_key="key"&format=1')
rates = response["quotes"]
rates.each do |k,v|
create!(
date: Time.at(response["timestamp"]),
country_code: "#{k}",
price: "#{v}")
end
end
end
在控制器中:
def index
Realtimerate.get_cl_rates
@realtimerates = Realtimerate.all
end
这正在运行并显示最新的 GET。
【问题讨论】:
标签: ruby-on-rails json parameters httparty