ruby-on-rails

Rails: Grouping inside groups…

Follow me
Follow me

Latest posts by Tomasz Antas (see all)

Nov 12, 2015

Post is about grouping objects inside parent groups.

Let’s assume that there is the Task model and it includes fields: name, description, task_status, user.

The goal is to get all Tasks firstly grouped by task_status. Then inside of each group, we group again by user attribute.

The goal is to achieve following structure:

rails_grouping_ppost

 

 

Following Rails instruction allows us to get desired result:

You may prefer to modify code above. For example, if you want use whole object in mapping as a key, you can remove “.name”.

If you want preview the structure of @tasks_grouped_by_status_and_users, you may display it temporary in view as json:

Then open view in web browser and object as a JSON should be placed in view. You can copy it and display in nice format in one out of the online JSON viewers (like http://jsonviewer.stack.hu/).

Tomasz AntasRails: Grouping inside groups…
  • http://imgdj.com Iris Panabaker

    I would also recommends http://codebeautify.org/jsonviewer and http://jsonformatter.org for JSON test , Save and Share JSON Data

  • karthick

    iris

  • sonu

    @tasks_grouped_by_status_and_users = Task.all.group_by {|t| t.task_status }.map { |k,v| [k, v.group_by { |s| s.user}.map { |t,r| [t, r]} ] } this work