Jbuilder:我如何合并2个顶级数组?

时间:2012-05-10 08:42:51

标签: ruby-on-rails ruby ruby-on-rails-3 json jbuilder

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

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"}]"

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

3 个答案:

答案 0 :(得分:5)

我知道两个选项:

  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
    
  3. 在这两种情况下,都不需要调用#to_json或类似的东西。

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

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