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.
CodePudding user response:
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.
serialize :incorrect, Array
CodePudding user response:
Change your migration field for "incorrect" from
t.string "incorrect"
to:
t.text :incorrect, array: true, default: []
Also I suggest you to use symbols instead of strings for column names and use t.timestamps
that generates created_at
and updated_at
for you