I am wondering how I can make this work. Assuming I have a model of Project that belongs_to a Client. I want to output those particular projects to JSON, but they need to be grouped by their client. I thought this would work:
@projects.group_by(&:client).to_json
That ALMOST works, except the to_json method isn’t calling .to_json on the client, so for the client you get this in your JSON:
"#<Client:0x1051d4fb0>":[{ "project":{"name":"My Only Project", "client_id":1}}]
But I really need it like this:
{"client":{"name":"Home Workers Unite", "id":1, "projects":[{"name":"My Only Project","client_id":1}]}}
Any help is appreciated!
As already told by @LarryK, the json you want as out put is not a valid json. In json keys can only be strings unlike ruby which can has objects as keys. Also, I would suggest that the json response be more like following:
You already have projects available with you. You also have the code to group them by client, but a simple
to_jsonon the resulting hash would not be suitable here. You would need to manipulate the grouped response further to be able to directly useto_json:This is ruby/rails version of the solution. However if you have a json heavy application, I would suggest using some gem(jbuilder, rabl, or any other) to create the desired responses.
PS: code is not tested