简体   繁体   中英

how to split the array and store into the database in ruby on rails?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM