Question

I'd like to be able to create some super simple json string with jbuilder since it's included in rails 4 by default.

Say I got some Categories current_project.categories.

At the moment I'm using this jbuilder construct to get only the category titles:

json.array! current_project.categories do |c|
  json.title c.title
end

This genervtes the following response:

[{"title":"Allgemeine Fragen"},{"title":"Dauerkarten"},{"title":"Heimspiele"},{"title":"Online-Ticketing"},{"title":"Rollstuhlfahrer"},{"title":"Auswärtsspiele"},{"title":"Busfahrten"},{"title":"Meine Kategorie"},{"title":"Meine neue Kat"}]

It would be nice if I could keep that json response way more simple, e.g.:

["Allgemeine Fragen", "Dauerkarten", "Heimspiele", "Online-Ticketing", "Rollstuhlfahrer", "Auswärtsspiele", "Busfahrten", "Meine Kategorie", "Meine neue Kat"]

How can I accomplis this using jbuilder?

Thanks!

Was it helpful?

Solution

You can use

json.array! current_project.categories.pluck(:title)

or the extended version

json.array! current_project.categories.map(&:title)

The first is more efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top