How to group on status and output in JSON

442 Views Asked by At

I am creating a Rails 5 app. In this app I got Candidate models. Each Candidate got a status attribute. I want to create a JSON (Jbuilder) output that looks like below. Meaning I want to group the output on Status attribute of each Candidate.

[{
        "total_entries": 1
    },
    {
        "entries": [{
            "pending": [{
                "id": 4,
                "name": "James Britain"
            }],
            "completed": [{
                "id": 4,
                "name": "James Britain"
            }, {
                "id": 4,
                "name": "Anna Tompson"
            }]
        }]
    }
]

I tried the following but that did not work.

Candidate.select('status, firstname').group('status, firstname')

Please help!

1

There are 1 best solutions below

2
Billy Ferguson On

You have to use group_by and the syntax is slightly different based on your db and version of rails. Supplying those would help nail down the answer, but this is the widest usecase:

Candidate.select('status, firstname').group_by(&:status)