有没有办法用一系列字符串值播种钥匙?
我正在尝试使用外部琐事API播种一些数据。
这是我在seeds.rb文件中所拥有的,其中httparty是一个将json解析为ruby hash的宝石:
response = HTTParty.get("THE-API-SITE")
response.each do |trivia|
triviaHash = {
category: trivia["category"],
answer: trivia["correctAnswer"],
incorrect: trivia["incorrectAnswers"],
question: trivia["question"],
}
Trivia.find_or_create_by(triviaHash)
end
这是我的架构:
create_table "trivia", force: :cascade do |t|
t.string "category"
t.string "answer"
t.string "incorrect"
t.string "question"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "ids"
end
除了“不正确”的键外,其他所有内容都应该具有一系列错误的答案字符串的值,但是当我播种数据时,我会得到一串不正确的答案。
我想要的:
incorrect: ["Deep Purple", "Feeder", "Uriah Heep"],
我得到的:
incorrect: "["Deep Purple", "Feeder", "Uriah Heep"]",
我不确定如何获得我想要的东西,或者是否可能像我要做的那样。
I'm trying to seed some data using an external trivia API.
Here's what I have in my seeds.rb file where HTTParty is a gem that parses JSON into a ruby hash:
response = HTTParty.get("THE-API-SITE")
response.each do |trivia|
triviaHash = {
category: trivia["category"],
answer: trivia["correctAnswer"],
incorrect: trivia["incorrectAnswers"],
question: trivia["question"],
}
Trivia.find_or_create_by(triviaHash)
end
And here's my schema:
create_table "trivia", force: :cascade do |t|
t.string "category"
t.string "answer"
t.string "incorrect"
t.string "question"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "ids"
end
Everything works except for the "incorrect" key which should have a value of an array of strings of incorrect answers, but when I seed my data, I get a string of the array of incorrect answers.
What I want:
incorrect: ["Deep Purple", "Feeder", "Uriah Heep"],
What I'm getting:
incorrect: "["Deep Purple", "Feeder", "Uriah Heep"]",
I'm not sure how to get what I want or if it's even possible the way I'm going about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您的列
不正确
是类型字符串,因此存储在DB中的数据也将是字符串值。如果您的数据库支持数组数据类型,则可以使用它,否则我建议您在模型中使用它。
Since your column
incorrect
is of type string, so the data stored in DB will also be a string value.If your DB supports array data type then you can use that or else I would suggest you to use this in your model.
更改
不正确
字段的迁移字段,从:TO:
也建议您使用符号而不是字符串作为列名称,并使用
t.timestamps
生成create> create> created_at
和更新
for for youChange your migration field for
incorrect
field, from:to:
Also I suggest you to use symbols instead of strings for column names and use
t.timestamps
that generatescreated_at
andupdated_at
for you