Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails use SQL group_by

I got a model call Answer, and here is its table

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

I need to return a array or json format include every group_id and their different qset_id

Maybe like this

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

I thought about group_by, but I am stuck here. And the table is very large, is there a efficient Rails way to handle that?

like image 799
Coda Chang Avatar asked Aug 23 '26 21:08

Coda Chang


1 Answers

Have you tried this ?

@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

I created a test here for this and I received the correct answer.

[email protected] (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"}
like image 83
Breno Perucchi Avatar answered Aug 26 '26 16:08

Breno Perucchi