Reputation: 2273
How do I split this array and store into the database?
I have three fields in my model called Question_id, Answer_id and Phase_id
.
I have a result like:
question_hash_string = "{\"5\":[\"5\",\"0\",\"\"],\"25\":[\"25\",\"1\",\"3\"]}"}
Which looks like {5:[5,0,1], 25:[25,1,3] ... }
.
I want to split the array and store the results into the three fields in order Question
, Answer
and Phase
of each set.
In my Batch
table, I have three columns: question_id
, answer_id
and phase_id
.
The first value of array[5,0,1]
, 5
goes to question_id
, 0
to answer_id
and 1
to phase_id
. In the second row 25
to question_id
, 1
to answer_id
and 3
to phase_id
.
Upvotes: 0
Views: 602
Reputation: 10137
You can do this:
hash_values = JSON.parse(question_hash_string)
hash_values.each do |k,v|
b = Batch.new
b.question_id, b.answer_id, b.phase_id = v.collect(&:to_i)
b.save!
end
Upvotes: 3
Reputation: 211670
You should be able to parse this with JSON:
json_loaded = JSON.load(question_hash_string)
From there you can emit in any format you might wish, but will need to convert your values to integers:
remapped = Hash[
json_loaded.collect do |k, a|
[ k.to_i, a.collect(&:to_i) ]
end
]
# => {5=>[5, 0, 0], 25=>[25, 1, 3]}
JSON.dump(remapped)
# => {"5":[5,0,0],"25":[25,1,3]}
Since JSON requires string keys, this is very close to what you want. To get it precisely the same you'd have to write a custom emitter.
Upvotes: 2