Morris
Morris

Reputation: 520

How can I create group objects by a field

I have a table in my app that has the following fields: room, start_at, title and panel.

I want to query them divided by rooms, for example, so I can have a json just like this:

{
  "rooms": {
    "Asia": [{
        "title": "Asia 1",
        "panel": "Asia 1"
    }, {
        "title": "Asia 2",
        "panel": "Asia 2"
    }],
    "Europe": [{
        "title": "Europe 1",
        "panel": "Europe 1"
    }, {
        "title": "Europe 2",
        "panel": "Europe 2"
    }]
  }
}

How can I achieve it?

Upvotes: 0

Views: 36

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15055

Since you're using Rails, it can be performed as following:

grouped_rooms = Room.all.group_by(&:room)
grouped_rooms_json = grouped_rooms.transform_values do |room|
  room.as_json(only: [:id, :created_at])
end
{ "rooms" => grouped_rooms_json }

Upvotes: 2

Related Questions