3

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?

0

1 Answer 1

2

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"}
Sign up to request clarification or add additional context in comments.

2 Comments

I am not sure, cause it took to long and the result didn't show. The Answer is very huge (more than 10 million record)
So you need to do this action directly in sql

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.