Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 347
melekes Avatar asked May 10 '12 08:05

melekes


2 Answers

I know of two options:

  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
    

In both cases, there's no need to call #to_json or similar.

like image 164
Yuri Gadow Avatar answered Oct 04 '22 03:10

Yuri Gadow


Yuri's answer got me close, but the ultimate solution for me was simply doing this in my .jbuilder file.

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

The order I put the arrays in is the order the array was combined.

like image 26
andyrue Avatar answered Oct 04 '22 03:10

andyrue