首页 > 解决方案 > 使用嵌套数据调用 API,得到“TypeError:没有将 String 隐式转换为 Integer”

问题描述

我正在通过调用 Rails 后端中的 API 来制作一个反应应用程序,我想将其播种到数据库中,API 返回

{
   "_id": "5e96659e6a66e65486e24493",
   "content": "And I knew exactly what to do. But in a much more real sense, I had no idea what to do.",
   "character": {
     "_id": "5e93b4a43af44260882e33b0",
     "firstname": "Michael",
     "lastname": "Scott",
     "__v": 0
   },
   "__v": 0
 } 

我想获取内容和角色,以及我的数据库中的名字和姓氏以及种子,以便在我的前端调用。目前在我的后端我有一个表迁移

class CreateQuestions < ActiveRecord::Migration[6.1]
  def change
    create_table :questions do |t|
      t.string :content
      t.string :character

      t.timestamps
    end
  end
end 

我有一个控制器

    before_action :set_question, only: [:show, :update, :destroy]

  def index
    @questions = Question.all

    render json: @questions, only: [:content, :character, :id]
  end

end

在我的种子文件中

require 'rest-client'

 resp = RestClient::Request.execute(method: :get,
 url: "https://officeapi.dev/api/quotes/",
 headers:{
     'Content-Type': 'application/json'
 })

resp_array = JSON.parse(resp)

resp_array.each do |question|
    Question.create(
       id: question["id"],
       content: question["content"],  
       character: question["character"]
    )
end

和架构

ActiveRecord::Schema.define(version: 2021_09_29_183742) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "questions", force: :cascade do |t|
    t.string "content"
    t.string "character"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

我认为这会起作用,但是当我去运行 rake db:seed 时,我得到一个“TypeError:没有将字符串隐式转换为整数”我相信这是因为字符哈希中的嵌套 id、firstname、lastname 或不正确的方式我已经设置好了。任何帮助,将不胜感激!

标签: ruby-on-railsapibackendrake

解决方案


也可能存在问题,因为从 API 返回的 id ("5e96659e6a66e65486e24493") 是字符串,而数据库中的 id 列将是整数类型。也许将 API 中的 id 保存在单独的列中(guid?)。

之后,嵌套的字符字段也有可能会导致问题。您可以序列化哈希,但我的建议是将字符存储在单独的表中。这两个表可能如下所示:

quotes
------
id
guid
content
character_id

characters
----------
id
guid
first_name
last_name

推荐阅读