简单的自定义jbuilder json响应 [英] Simple custom jbuilder json response

查看:136
本文介绍了简单的自定义jbuilder json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用jbuilder创建一些超级简单的json字符串,因为默认情况下它包含在rails 4中.

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

说我有一些类别current_project.categories.

此刻,我正在使用此jbuilder构造仅获取类别标题:

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

这会产生以下响应:

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

如果我可以使json响应方式更简单,例如:

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"]

我如何使用jbuilder来实现这一目的?

How can I accomplis this using jbuilder?

谢谢!

推荐答案

您可以使用

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

或扩展版本

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

第一个更有效.

这篇关于简单的自定义jbuilder json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆