Adding a hash to jsonb column in active record

时间:2018-07-24 10:02:31

标签: ruby-on-rails postgresql

I am returning a params hash in a controller.

params[:questions] = {"ad6d1d19-f95b-228c-8a19-49150ad15f23"=>"answer21", "90783719-9cd6-23de-f3fb-9bc80e7a72a0"=>"answer22"}

With multiple key value pairs. I have model Model1. This has a json column called answers. Every time a params[:questions] is returned. I'm trying a create a Model1 object as follows:

Model1.create(answers: {q_id: the_id, ans: the_answer})

How can I create multiple key value pair answers column? If I iterate through the params[:questions] and create an object, it will create a new object for every pair. So that's not a solution.

1 个答案:

答案 0 :(得分:0)

这项工作吗?

m = Model1.new
params[:questions].each do |id, answer|
  m.answers << {q_id: id, ans: answer}
end
m.save!

或者也许

hash = {} 
params[:questions].each do |id, answer|
  hash << {q_id: id, ans: answer}
end
Model1.create(answers: hash