【问题标题】:Return nested array with Ruby Grape in Rails 5在 Rails 5 中使用 Ruby Grape 返回嵌套数组
【发布时间】:2017-12-14 00:50:52
【问题描述】:

我已经成功构建了一个api,你可以看到here,代码如下。我需要将对象列为嵌套数组而不是对象数组,但我无法弄清楚。

api/v1/plaques.rb

module API  
    module V1
      class Plaques < Grape::API
        include API::V1::Defaults

        resource :plaques do
          desc 'Return all Plaques'
          get '', root: :plaques do
            Plaque.all
          end

          desc 'Return a Plaque'
          params do
            requires :id, type: String, desc: 'ID of Plaque'
          end
          get ':id', root: 'plaque' do
            Plaque.where(id: permitted_params[:id]).first!
          end
        end
      end
    end
  end 

我得到了什么:

[
    {
    "veteran_first": "Alexis",
     ...
    }
]

我需要什么:

 "items" =  [
        {
        "veteran_first": "Alexis",
         ...
        }
    ]

【问题讨论】:

  • 不太明白你说的最后一段代码是什么意思。你想要像 { "items": [ {}, {}, ... ] } 这样的 JSON 吗?
  • @user3309314 抱歉,我写的有点快——是的,这就是我要找的。​​span>
  • 返回{ items: Plaque.all } 做你想做的事吗?
  • @user3309314 工作就像一个魅力!请创建答案,以便我可以除外。谢谢!

标签: ruby-on-rails arrays ruby ruby-on-rails-5 grape-api


【解决方案1】:

此代码返回您想要的 JSON:

get '', root: :plaques do
  { items: Plaque.all }
end

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多