【问题标题】:Rails jbuilder remove headerRails jbuilder删除标题
【发布时间】:2013-01-29 05:45:21
【问题描述】:

我正在将 jbuilder 添加到 Rails 应用程序 - 很棒的工具!

我得到了我想要的记录列表,但它有我不想要的额外输出。

这是jbuilder代码:

json.locations @locations do |location|
 json.id location.id
 json.name location.name
end

输出是:

{
  - locations: [
    {
      id: 1,
      name: "Name 1"
    },
    {
      id: 2,
      name: "Name 2"
    },

我需要的是:

[
    {
      id: 1,
      name: "Name 1"
    },
    {
      id: 2,
      name: "Name 2"
    },

如何删除 { - 位置:

???

谢谢!!

更新:

我希望 jbuilder 有一行代码可以排除根目录。

【问题讨论】:

  • 我需要在返回对象时排除根元素 @foo = { bar: true, dry: false } json.foo @foo 将打印 {"foo": { "bar": true, "dry": false }} 并使用 merge! 函数我成功了 json.merge! @foo 给出了我想要的输出 {"bar": true, "dry": false}

标签: ruby-on-rails-3 jbuilder


【解决方案1】:

你能检查一下你是否有以下配置吗?

ActiveRecord::Base.include_root_in_json = false

这应该可以解决问题

更新

试试这个:

json.array!(@locations) do |location|
 json.id location.id
 json.name location.name
end

【讨论】:

  • 感谢您的帮助!我不确定要查看哪个文件?
  • 我相信是config/application.rb
  • 但是,这将为所有 json 提要删除它。正确的?我在另一个 q/a = my_model.to_json(:root => false) 上看到了这段代码。但是,我使用的是 jbuilder,所以我的控制器中没有 json 语句。
  • 我希望 jbuilder 有一行代码可以排除根目录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 2014-06-16
  • 1970-01-01
  • 2018-02-13
  • 2019-04-06
  • 2020-06-21
  • 2023-04-09
相关资源
最近更新 更多