ruby-on-rails - 使用嵌套数据调用 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 或不正确的方式我已经设置好了。任何帮助,将不胜感激!
解决方案
也可能存在问题,因为从 API 返回的 id ("5e96659e6a66e65486e24493") 是字符串,而数据库中的 id 列将是整数类型。也许将 API 中的 id 保存在单独的列中(guid?)。
之后,嵌套的字符字段也有可能会导致问题。您可以序列化哈希,但我的建议是将字符存储在单独的表中。这两个表可能如下所示:
quotes
------
id
guid
content
character_id
characters
----------
id
guid
first_name
last_name
推荐阅读
- angular - 向 mat 表单字段添加验证
- docker - Docker hub 不断超时并在大镜像层上重试直到失败
- c - 用 C 求方程的根
- c# - 将变量从类返回到 MainForm
- java - Struts 2 - 从数据库填充下拉列表
- powershell - 如何添加/替换 psobject
- ruby-on-rails - heroku .rvm/gems/ruby-2.4.0/bin/heroku:没有这样的文件或目录
- c++ - 是否有类似于 std::lower_bound 的函数而不需要排序/分区输入?
- django - 如何将特定用户下的数据放入 Django 中的模板中
- c# - c# windows窗体如何让图片框跟随光标