1

I am working with rails API , and I want to render JSON file but with specific way. I have a model with named Store, and in this model, i have records like State and City. My problem is that I want render JSON to looks like this:

{ 
"Arizona": [
      "Phoenix",
      "Tucson"
    ],
    "California": [
      "Anaheim",
      "Los Angeles",
      "San Diego",
      "San Francisco"
    ],
    "Colorado": [
      "Denver"
    ],
}

I may have in model many records with the name Colorado or with the name California, but every California record have its own city name, for example:

this is my model

|  state   |   city   |
-----------------------
|California| Anaheim  |
|Colorado  | Denver   |
|California| San Diego|

and so on ..

so I want to pair every city that belongs to the unique state, so my JSON would show only one time the State name .

any suggestion?

pureofpure
  • 1,060
  • 2
  • 12
  • 31

1 Answers1

2

Try this:

Model.select(:state, :city).group{|add| address.state}

This will return:

{"California" => [ModelObject2, ModelObject2 ], "Colarado" => [ModelObject1]}

Now we need to replace second object part with the city name so loop over the second part and get city from that object and then to_json to convert into json object.

Model.select(:state, :city).group{|add| address.state}.each{|_, v| v.replace(v.map {|add| add.city})}.to_json

Hope this will help you!!

ref

Community
  • 1
  • 1
Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56