【问题标题】:Adding a hash to jsonb column in active record向活动记录中的 jsonb 列添加哈希
【发布时间】:2018-07-24 19:10:35
【问题描述】:

我在控制器中返回一个参数哈希。

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

具有多个键值对。 我有模型 Model1。这有一个名为 answers 的 json 列。 每次返回 params[:questions] 时。我正在尝试创建一个Model1 对象,如下所示:

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

如何创建多个键值对answers 列?如果我遍历 params[:questions] 并创建一个对象,它将为每一对创建一个新对象。所以这不是一个解决方案。

【问题讨论】:

  • 你试过什么?你能显示一些代码吗?哪里不行?

标签: ruby-on-rails postgresql


【解决方案1】:

这行得通吗?

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

)

【讨论】:

    猜你喜欢
    • 2016-08-18
    • 1970-01-01
    • 2017-12-10
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2014-07-20
    • 1970-01-01
    相关资源
    最近更新 更多