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

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"}]" 有人可以帮帮我吗?提前感谢您。
3个回答

6

我知道两种选择:

  1. Combine the arrays before iterating, which works well with multiple source arrays of ducks:

    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. Or when you've got ducks and turkeys, combine the json arrays:

    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或类似的方法。

我该如何通过值将这些数组组合、排序并添加键? - Peter R
@PeterR 在第一个示例中,这两个数组正在被合并。为了在不让代码难以阅读的情况下进一步操作它们,请将组合从 #array!调用中提取出来,然后按照您喜欢的方式进行操作。我扩展了示例以显示可能的一种方法。 - Yuri Gadow

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

我把数组放置的顺序就是合并后的顺序。

-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

我本来想要更像「Jbuilder」的解决方案,但这个也不错。谢谢! - melekes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接