Simple custom jbuilder json response

佐手、 提交于 2019-12-12 01:06:42

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/20705271/simple-custom-jbuilder-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!