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

mel*_*kes 3 ruby json ruby-on-rails jbuilder ruby-on-rails-3

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

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

Yur*_*dow 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
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)

在这两种情况下,都无需调用#to_json或类似名称。


Tom*_*ing -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
Run Code Online (Sandbox Code Playgroud)