Search code examples
ruby-on-railsrubyruby-on-rails-3jsonjbuilder

Jbuilder: How I can merge 2 top level arrays?


I have two top level arrays, which have the same format. And I want to merge them:

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

So the output would be as follows: "[{value: "a", href: "/sample1"}, {value: "b", href: "/sample2"}]"

But the code above doesn't work. It includes only the second array: "[{value: "b", href: "/sample2"}]"

Could someone help me? Thanks in advance.


Solution

  • 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