Skip to content

Instantly share code, notes, and snippets.

@aamax
Created July 14, 2015 17:09
Show Gist options
  • Save aamax/0556b89c1537b45354d4 to your computer and use it in GitHub Desktop.
Save aamax/0556b89c1537b45354d4 to your computer and use it in GitHub Desktop.
how to do JSON return in this format?
I have a model that looks like:
# == Schema Information
#
# Table name: vendors
#
# id :integer not null, primary key
# company_name :string
# category :string
#
in my index action (of my API) I want to return Vendor.all but the data needs to be re-organized. Here's an example:
for this active record set:
[
{id: 1, company_name: 'co1', category: 'cat1'},
{id: 1, company_name: 'co2', category: 'cat1'},
{id: 1, company_name: 'co3', category: 'cat2'},
{id: 1, company_name: 'co4', category: 'cat2'},
{id: 1, company_name: 'co5', category: 'cat2'}
]
I want to return something like this:
[
{'cat1' => [
{company_name: 'co1'}, {company_name: 'co2'}
]
},
{'cat2' => [
{company_name: 'co3'}, {company_name: 'co4'},{company_name: 'co5'}
]
}
]
how can I do that?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment