5

我有两个顶级数组,它们具有相同的格式。我想合并它们:

json = Jbuilder.encode do |json|
  json.(companies) do |json, c|
    json.value c.to_s
    json.href employee_company_path(c)
  end
  json.(company_people) do |json, cp|
    json.value "#{cp.to_s} (#{cp.company.to_s})"
    json.href employee_company_path(cp.company)
  end
end

所以输出如下:"[{value: "a", href: "/sample1"}, {value: "b", href: "/sample2"}]"

但是上面的代码不起作用。它仅包括第二个数组:"[{value: "b", href: "/sample2"}]"

有人可以帮助我吗?提前致谢。

4

3 回答 3

6

我知道两种选择:

  1. 在迭代之前组合数组,这适用于鸭子的多个源数组:

    def Employee
      def company_path
        self.company.company_path if self.company
      end
    end
    
    [...]
    
    combined = (companies + company_people).sort_by{ |c| c.value }
    # Do other things with combined
    
    json.array!(combined) do |duck|
      json.value(duck.to_s)
      json.href(duck.company_path)
    end
    
  2. 或者当你有鸭子和火鸡时,组合 json 数组:

    company_json = json.array!(companies) do |company|
      json.value(company.to_s)
      json.href(employee_company_path(company))
    end
    
    people_json = json.array!(company_people) do |person|
      json.value(person.to_s)
      json.href(employee_company_path(person.company))
    end
    
    company_json + people_json
    

在这两种情况下,都不需要调用 #to_json 或类似的方法。

于 2015-10-29T00:08:48.210 回答
3

Yuri 的回答让我很接近,但对我来说最终的解决方案就是在我的.jbuilder文件中这样做。

json.array!(companies) do |company|
  json.value(company.to_s)
  json.href(employee_company_path(company))
end

json.array!(company_people) do |person|
  json.value(person.to_s)
  json.href(employee_company_path(person.company))
end

我放入数组的顺序是组合数组的顺序。

于 2017-09-26T19:58:02.683 回答
-1
result =  []
companies.each do |c|
  result << {:value => c.to_s, :href => employee_company_path(c)
end
company_people.each do |c|
  result << {:value => "#{cp.to_s} (#{cp.company.to_s})", :href => employee_company_path(cp.company)
end
# at this point result will be an array of companies and people which just needs converting to json.
result.to_json
于 2012-05-10T10:04:54.873 回答