Rails使用SQL group_by

时间:2016-08-10 02:10:57

标签: mysql sql ruby-on-rails json activerecord

我有一个模型调用Answer,这是它的表

id      group_id    qset_id 
1       123            1
2       123            2
3       123            1
4       456            1
5       456            1
6       456            3

我需要返回arrayjson格式,包括每个group_id及其不同的qset_id

也许就像这样

class: [
    {
        "group_id": 123
        "qset_id": [1,2]
    },
    {
        "group_id": 456
        "qset_id": [1,3]
    }
]

我想过group_by,但我被困在这里。并且表非常大,是否有一种高效的Rails方式来处理它?

1 个答案:

答案 0 :(得分:1)

你试过这个吗?

@answer = Answer.all.group_by(&:group_id) 

@answer.each_with_index do |answer, index|
  {
   'group_id': index,
   'qset_id: answer.flatten.map{|x| x_id}
  }    
end
I have to tell that I had to study more query sql to find this solution

ActiveRecord::Base.connection.exec_query('SELECT group_id, GROUP_CONCAT(qset_id) FROM answers GROUP BY group_id').rows.to_h

我为此创建了一个测试,我收到了正确的答案。

4.1.15@2.2.0 (main)> ActiveRecord::Base.connection.exec_query('SELECT proposal_id, GROUP_CONCAT(DISTINCT unit_id) FROM bookings GROUP BY proposal_id').rows.to_h
  SQL (0.2ms)  SELECT proposal_id, GROUP_CONCAT(DISTINCT unit_id) FROM bookings GROUP BY proposal_id
=> {1=>"2,3", 3=>"4", 4=>"5", 5=>"6"}