ruby-on-railsjsonjbuilder

Inlined array elements with JBuilder


How do you create an array with elements in it using Jbuilder without setting it to a variable first?

I want to end up with the following while using JBuilder

{
  "something": [
    { "name": "first", "foo": "bar"},
    { "name": "second", "foo": "baz"}
  ]
}

The only method I have found that works is the following.

json.something do
  something = [
    { name: 'first', foo: 'bar' },
    { name: 'second', foo: 'baz' }
  ]
  json.array! something do |item|
    json.(item, :name, :foo)
  end
end

Is there a way to make it look more like this?

json.array! 'something' do
  json.array do
    json.name 'first'
    json.foo 'bar'
  end
  json.array do
    json.name 'second'
    json.foo 'baz'
  end
end

Solution

  • The only thing similar that I can imagine is use hardcoded hash:

    json.something do
       json.array! [
         {name:'first',foo:'bar'},
         {name:'second',foo:'baz'}
       ]
    end