如何在对象中包装对对象的数组响应

时间:2018-11-08 03:04:57

标签: ruby-on-rails

所以我有一个名为history的模型,然后我想渲染它。

我当前的代码如下:

class Address < ActiveModel::Serializer
  attributes :guid, :name, :address, :latitude, :longitude, :place_id, :notes, :last_used_on

  def latitude
    object.latitude.to_s
  end

  def longitude
    object.longitude.to_s
  end
end

响应是

[
  {
    "guid"=>"Address-35-91526dee",
    "name"=>"Lake Johana",
    "address"=>"Apt. 951 774 Bruen Mountains, Schneiderchester, OK 90705-0506",
    "latitude"=>"67.24423261517666",
    "longitude"=>"96.37355099166064",
    "place_id"=>"ltpzw5n87w",
    "notes"=>"c2rxzesry7",
    "last_used_on"=>"2018-11-05 09:56:23 +0700"
  },
  {
    "guid"=>"Address-34-23f95e54",
    "name"=>"North Gregoryshire",
    "address"=>"64213 Vandervort Trail, North Marinville, CA 70667",
    "latitude"=>"-45.928682957769965",
    "longitude"=>"124.27899877429144",
    "place_id"=>"hwki1m0xwg",
    "notes"=>"k34un21zjh",
    "last_used_on"=>"2018-11-05 09:56:23 +0700"
  }
]

我想要的是将响应包装在addresses内,这样看起来就像

{
  "addresses": [
    {
      "guid": "AddressHistory-16-58abd401",
      "name": "Port Charla",
      "address": "5016 Kerstin Brook, West Tanja, MO 02060",
      "latitude": "-68.07486131158515",
      "longitude": "-8.531218394535387",
      "place_id": "9guhaf7o1e",
      "notes": "rl5qq7r7cv",
      "last_used_on": "2018-11-05 09:42:51 +0700",
    },
    {
      "guid": "AddressHistory-15-86bea685",
      "name": "South Vernon",
      "address": "1185 Tania Road, South Joeyborough, OK 97125",
      "latitude": "84.52009358082654",
      "longitude": "87.74343692672034",
      "place_id": "hiw08eeh0l",
      "notes": "8nn5aiwe9m",
      "last_used_on": "2018-11-05 09:42:51 +0700",
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

a=Hash.new
a['addresses']=response