我是rails的新手,对于如何从API调用中获取JSON字符串并将其存储到我的模型中有点迷失。我正在试图解决这个问题。
作为示例,我从API调用中收到以下内容。
{“FileType”=> nil,“Text”=> nil,“TextCode”=> nil,“Html”=> nil, “HtmlCode”=> nil,“Rtf”=> nil,“RtfCode”=> nil,“CreditsRemaining”=> 0, “FileExtension”=> nil,“Pdf”=> nil,“PdfCode”=> nil, “CandidateImage”=> nil,“CandidateImageExtension”=> nil, “Code”=>“错误”,“SubCode”=>“AuthenticationError”,“消息”=>“无效 AccountId:您提供的“AccountId”无效。“, “ParsedDocument”=>零}
我想将此插入到简历模型中,因此我创建了以下帮助。
require 'rest-client'
require 'base64'
require 'json'
module ResumesHelper
def parser
FILE_NAME = "test.docx"
# Perform a binary read of the entire file
fileBuf = File.open(FILE_NAME,"rb") {|io| io.read}
base64 = Base64.encode64(fileBuf)
params = "{\"FileBytes\":" + "\"" + base64 + "\"," +
"\"AccountId\": \"MyID\",
\"ServiceKey\": \"MyKey\"}"
response = RestClient::Request.execute(
method: :post,
url: 'http://example/api',
payload: params,
headers: {"Content-Type" => "application/json"}
)
a_hash = JSON.parse(response)
new_record = Resume.new
new_record.attribute_1 = a_hash['Message']
new_record.save
end
我收到一条错误,指出脚本的语法不正确。请让我知道我在这里做错了什么或指向正确的方向。
答案 0 :(得分:0)
这就是我将来需要保存JSON返回时的操作。
1)迁移 rails g migration AddJsonResponseToModel
#/db/migrate/20170518014529_add_json_response_to_model.rb
class AddJesonResponseToModel < ActiveRecord::Migration[5.0]
def change
add_column :models, :json_response, :text
end
end
2)控制器或者你得到了回应
#app/controllers/models_controller.rb
class ModelsController < ApplicationController
def create
model = Model.find(params[:id])
response = RestClient::Request.execute(
method: :post,
url: 'http://example/api',
payload: params,
headers: {"Content-Type" => "application/json"}
)
model.json_response = response.to_json
...
model.save
end
end
我希望这适合你:) 快乐黑客