Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 351
Jason Avatar asked Jun 27 '14 21:06

Jason


2 Answers

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.

like image 195
Carlosin Avatar answered Oct 18 '22 07:10

Carlosin


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
like image 29
Ruby Racer Avatar answered Oct 18 '22 08:10

Ruby Racer