6

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
Jason
  • 3,736
  • 5
  • 33
  • 40

2 Answers2

18

it turns out that jbuilder has built-in support for this kind of usage. You can use child! method in this way:

json.something do
  json.child! do
    json.name "first"  
    json.foo "bar"
  end
  json.child! do
    json.name "second"
    json.foo "barz"
  end
end

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

it is much better, I think.

rewritten
  • 16,280
  • 2
  • 47
  • 50
Carlosin
  • 509
  • 6
  • 9
6

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
Ruby Racer
  • 5,690
  • 1
  • 26
  • 43