Rails将多个对象合并为一个数组

时间:2018-06-11 10:53:05

标签: ruby-on-rails json api

我正在创建API。使用ActiveRecords。我遇到的问题 国家的多个数组对象,我想要一个包含所有位置的数组

当前输出

{
  "id": "180a096",
  "country": [
      {
          "location": "US"
      },
      {
          "location": "CH"
      }
  ]
}

预期输出

{
  "id": "180a096",
  "country": [
      {"location":["US","CH"]}
  ]
}

代码

  def as_json(options={})
   super(:only => [:id ],:include => { :country => { :only => :location } })
  end

任何人都可以帮我按预期的输出重组对象。

4 个答案:

答案 0 :(得分:0)

如果你的哈希被称为hash,你可以这样做:

hash[:country].map {|h| h[:location]}

如果您必须访问相关模型上的属性,您可以执行以下操作:

countries.pluck(:location)

与此问题无关,但当我必须在我的应用中管理国家/地区信息时,我倾向于使用countries gem。 https://github.com/hexorx/countries

它有各种有用的辅助方法,它可以防止您必须维护标准化的国家/地区信息。

答案 1 :(得分:0)

您可以简单地映射所有位置并将其分配给哈希[:country]

 2.4.0 :044 > hash[:country].map! { |c| c[:location] }
 => ["US", "CH"] 
 2.4.0 :045 > hash
 => {:id=>"180a096", :country=>["US", "CH"]} 

答案 2 :(得分:0)

我的评论中所述,您可以在一行中执行

actual_hash[:country].map! { |country| country[:location]}
actual_hash # => {:id=>"180a096", :country=>["US", "CH"]}

输出干净但不符合预期。

或者,更多一行来获得准确的输出:

location_array = [{location: []}]
actual_hash[:country].each { |country| location_array[0][:location] << country[:location]}
actual_hash[:country] = location_array
actual_hash # => {:id=>"180a096", :country=>[{:location=>["US", "CH"]}]}

答案 3 :(得分:0)

def rearrange_json(input)
  input_hash = JSON.parse(input)
  output_hash = input_hash.clone
  output_hash[:country] = {location: []}
  input_hash[:country].map {|l| output_hash[:country][:location] << l[:location] }
  output_hash.as_json
end

使用此方法,您可以将json转换为哈希值,然后通过将国家/地区代码添加为输出哈希的[:country][:location]键的值来重新排列其所需内容,并最终得到一些正确的结果格式化的json。它不是一个单行,也可能不是最优雅的方式,但它应该有效。

相关问题