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?
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With