在葡萄 api 中添加了根,但未包含在响应中

added root in grape api but not included in response

我正在关注 this article to learn about writing api using grape gem。但是在响应中我没有得到根密钥。这是我的目录结构,

app
 |––controllers
       |––api
           |––base.rb
           |––v1
               |––base.rb
               |––graduates.rb

在app/controllers/api/v1/graduates.rb:

module API
  module V1
    class Graduates < Grape::API
      include API::V1::Defaults
  resource :graduates do
    desc "Return all graduates"
    get "", root: :graduates do
      Graduate.all
    end

    desc "Return a graduate"
    params do
      requires :id, type: String, desc: "ID of the 
        graduate"
    end
    get ":id", root: "graduate" do
      Graduate.where(id: permitted_params[:id]).first!
    end
  end
end

结束 结束

在app/controllers/api/v1/defaults.rb

module API
  module V1
    module Defaults
      extend ActiveSupport::Concern
  included do
    prefix "api"
    version "v1", using: :path
    default_format :json
    format :json
    formatter :json, 
         Grape::Formatter::ActiveModelSerializers

    helpers do
      def permitted_params
        @permitted_params ||= declared(params, 
           include_missing: false)
      end

      def logger
        Rails.logger
      end
    end

    rescue_from ActiveRecord::RecordNotFound do |e|
      error_response(message: e.message, status: 404)
    end

    rescue_from ActiveRecord::RecordInvalid do |e|
      error_response(message: e.message, status: 422)
    end
  end
end

结束 结束

我已经使用 grape-active_model_serializers gem 进行如下序列化, 在 app/serializers/graduate_serializer.rb

class GraduateSerializer < ActiveModel::Serializer
  attributes :id, :name
end

我得到了以下输出。 [{"id":1,"name":"aaaa"},{"id":2,"name":"bbbb"},{"id":3,"name":"cccc"},{"id":4,"name":"dddd"}]

但是当我在 app/controllers/api/v1/graduates.rb 文件中添加 get "", root: :graduates do 时,我期望得到以下输出,

{"graduates": [{"id":1,"name":"aaaa"},{"id":2,"name":"bbbb"},{"id":3,"name":"cccc"},{"id":4,"name":"dddd"}]}

我错过了什么。为什么 graduates 没有添加为 root。帮我解决这个问题。

脏修复:在 app/controllers/api/v1/graduates.rb

中使用
get "" do
    { graduates: Graduate.all }
end

或者您可以删除 gem grape-active_model_serializers、删除 class GraduateSerializer、从 defaults.rb 中删除行 formatter :json, Grape::Formatter::ActiveModelSerializers,然后添加 gem grape-entity 到Gemfile,安装它,添加代码到 app/app/entities/graduate_entity.rb:

class GraduateEntity < Grape::Entity
  root 'graduates', 'graduate'

  expose :id
  expose :name
end

更改 app/app/controllers/api/v1/graduates.rb 中的代码:

get "" do
  present Graduate.all, with: GraduateEntity
end

我和你遇到了类似的问题,我通过添加解决了它

ActiveModelSerializers.config.adapter = :json

config/initializers/serializer.rb

如果对您有帮助,请告诉我