When using JBuilder, how I can completely remove evidence of an empty array element from my output? For this code sample, assume that we have three users and the third user has a nil
address:
json.array! @users.each do |user|
unless user.address.nil?
json.name user.name
json.address user.address
end
end
The resulting JSON is:
[
{
"name":"Rob",
"address":"123 Anywhere St."
},
{
"name":"Jack",
"address":"123 Anywhere St."
},
{}
]
See that last, empty {}
at the end there. So any time the block passed to array!
returns nil
I end up with an empty element in the array, rather than a lack of element. Is there any easy way to tell JBuilder not to output those? Or do I just need to treat the output of array!
as a plain ol' array and then compact
or reject
elements that I don't want?
I think you can avoid your use case by first using reject
on the users, and only add the valid users to the array:
json.array! @users.reject { |user| user.address.nil? }.each do |user|
json.name user.name
json.address user.address
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