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
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.
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
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