0

Question: How can I make a grouped array like this?

event_id: 1, person_id: 1, tasks: [1, 2] 
event_id: 1, person_id: 2, tasks: [3] 
event_id: 2, person_id: 1, tasks: [4]

The givens:

Tasks table:

enter image description here

Event.rb:

has_many :tasks
has_many :people

Task.rb

belongs_to :event

Person.rb

belongs_to :event

My thoughts are to do something like this (doesn't work):

- @grouped_tasks = Task.all.group(:event_id, :person_id).each do |z|
  = z.event.id
  = z.member.id
  = z.tasks.collect{|r| r.task.name}.join(",")
  = z.tasks.pluck(:name)
6
  • What exactly you want is unclear. You want an array or a table or what? Just write down what you want as final product for 2 3 tasks. I think it is not complicated. Commented Jan 17, 2020 at 19:37
  • I'd use an has_and_belongs_to_many or an has_many :through association. You find out which to pick here. Commented Jan 17, 2020 at 19:39
  • @ARK - I want a table grouped like event_id: 1, person_id: 1, tasks: [1, 2] Commented Jan 17, 2020 at 19:41
  • @3limin4t0r - how would that help? Commented Jan 17, 2020 at 19:43
  • 1
    Please replace the "task table" with a Ruby object that readers can cut-and-paste to test code. Same with the array of hashes: arr = [{ event_id: 1, person_id: 1, tasks: [1, 2]}, {...}, {...}]. Notice that I assigned a variable (arr) to that array. That way readers can refer to that variable in answers and comments without having to define it. Please also assign a variable to the task table object. In general, do not use pictures of code or data. Commented Jan 17, 2020 at 20:48

2 Answers 2

2

Instead of using an SQL "GROUP BY" with group(:event_id, :person_id) you could instead group the results using Ruby with group_by. This way you've each individual record for each group.

- task_groups = Task.all.group_by { |task| [task.event_id, task.person_id] }
- task_groups.each do |(event_id, person_id), tasks|
  = event_id
  = person_id
  = tasks.pluck(:id).join(', ')
  = tasks.pluck(:name).join(', ')
Sign up to request clarification or add additional context in comments.

Comments

1

If you are using postgres, you can get the result using following query.

Task.all.group(:event_id, :person_id).select("event_id,person_id,array_agg(id) as tasks")

2 Comments

Yes, using postgres
Then you can achieve the result using this query.

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.