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.
I know of two options:
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With