Rails jbuilder: how to build a JSON from an array with the key equals to the array values

3.1k Views Asked by At


I'm a pretty new Rails developer, I'm using Jbuilder to build my view in the following way:

[:aaa, :bbb, :ccc].each do |value|
  json.value do |json| #<------ Here is my error!
    json.partial! foo.send(value)
  end
end

Everything works BUT the json.value, my response is the following (obviously):

[{
"value" => {...}
"value" => {...}
"value" => {...}
}]

I'd like to have this one instead:

[{
"aaa" => {...}
"bbb" => {...}
"ccc" => {...}
}]

Any ideas?

1

There are 1 best solutions below

0
On BEST ANSWER

From the guide:

To define attribute and structure names dynamically, use the set! method:

json.set! :author do
  json.set! :name, 'David'
end

# => "author": { "name": "David" }

The solution is so:

[:aaa, :bbb, :ccc].each do |value|
  json.set! value do |json|
    json.partial! foo.send(value)
  end
end