gpt4 book ai didi

ruby-on-rails - Rails 数组 group_by

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:07 26 4
gpt4 key购买 nike

我有一个数据库查询结果的动态对象数组。

USERNAME   choice_indx   legend
USER1 3 4
USER2 0 4
USER3 0 4
USER1 9 2
USER2 9 2
USER3 8 2
USER1 3 1
USER2 9 1
USER3 8 1

查询:

SELECT survey_answers.anonymous_user_id, survey_answers.choice_index, survey_questions.legend 
FROM `survey_answers`
LEFT JOIN surveys ON surveys.id = survey_answers.survey_id
LEFT JOIN survey_questions ON survey_questions.id = survey_answers.survey_question_id
WHERE (survey_questions.legend IN (1,2,4)) AND (survey_answers.track_id =2) AND (survey_answers.survey_id =2) AND (surveys.survey_type =2)

我怎样才能按用户分组并得到这样的结果:

final_array = {
"USER1" => [[3,4],[9,2],[3,1]],
"USER2" => [[0,4],[9,2],[9,1]],
"USER3" => [[0,4],[8,2],[8,1]]
}

我试过在 Rails 中使用 group_by,但结果与我想要的不一样。谁能帮我一把?谢谢。

最佳答案

假设 objects 是具有 anonymous_user_idchoice_indexlegend 属性的 ActiveModel 对象的可枚举,这将做你想做的:

objects.map {|obj| obj.values_at(:anonymous_user_id, :choice_index, :legend) }
.group_by(&:shift)

如果您在 ActiveRecord 查询中使用 pluck,则可以跳过 map,例如:

MyModel.where(...)
.pluck(:anonymous_user_id, :choice_index, :legend)
.group_by(&:shift)

编辑

回复你的评论,是的,虽然它不是那么干净:

MyModel.where(...)
.pluck(:anonymous_user_id, :choice_index, :legend)
.map {|vals| Hash[ %w[ __key__ c_idx legend ].zip(vals) ] }
.group_by {|hsh| hsh.delete("__key__") }

或者:

MyModel.where(...)
.pluck(:anonymous_user_id, :choice_index, :legend)
.each_with_object(Hash.new {|h,k| h[k] = [] }) do |(key, c_idx, legend), hsh|
hsh[key] << { "c_idx" => c_idx, "legend" => legend }
end

关于ruby-on-rails - Rails 数组 group_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33991179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com