【问题标题】:Storing JSON data in Rails Model在 Rails 模型中存储 JSON 数据
【发布时间】:2017-05-18 18:06:24
【问题描述】:

我是 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, “代码”=>“错误”、“子代码”=>“身份验证错误”、“消息”=>“无效 AccountId:您提供的‘AccountId’无效。", "ParsedDocument"=>无}

我想将此插入到我的 Resume 模型中,因此我创建了以下 Helper。

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

我收到一个错误,指出脚本的语法不正确。请让我知道我在这里做错了什么或指出正确的方向。

【问题讨论】:

  • (1) 您应该发布错误消息,因为这通常会有所帮助,并且 (2) 那是您的实际代码吗?如果是这样,至少,看起来你没有用end 关闭def。
  • \"ServiceKey\"这部分可能是错的

标签: ruby-on-rails json database


【解决方案1】:

当我需要保存 JSON 返回以供将来处理时,我会这样做。

1) 迁移 rails g 迁移 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

我希望这对你有用:) 快乐黑客

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2013-09-21
    相关资源
    最近更新 更多