使用Grape在Rails应用程序中包含关系

问题描述 投票:0回答:1

我正在API中返回一个资源(我是,使用Grape),但我还想返回关系对象(就像ember应用程序所期望的那样包含对象)。我怎样才能做到这一点?我的序列化器如下:

class JudgeSerializer < ActiveModel::Serializer
    attributes :ID, :FIRST_NAME, :LAST_NAME, :FULL_NAME
end

我的模特:

class Judge < ApplicationRecord
    self.primary_key = 'id'
    self.table_name = 'judge'
    has_many :judgecourts, class_name: 'Judgecourt', primary_key: 'ID',foreign_key: 'JUDGE_ID'
end

我以这种方式返回这个资源:

desc 'Return a specific judge'
route_param :id do
  get do
    judge = Judge.find(params[:id])
    present judge
  end
end

生成这样的东西会很好:

data
:
{type: "judges", id: "1", attributes: {…}, relationships: {…}}
included
:
Array(1)
0
:
{type: "judgecourts", id: "1", attributes: {…}}
ruby-on-rails grape grape-api
1个回答
0
投票

好吧,你的问题看起来有两个主题:

1.如何在ActiveModelSerializer中包含关系

通过调整活动模型序列化程序并添加关系,可以非常轻松地完成此操作,以便ActiveModelSerializer知道它必须包含序列化对象中的关系:

class JudgeSerializer < ActiveModel::Serializer
  attributes :ID, :FIRST_NAME, :LAST_NAME, :FULL_NAME

  has_many :judgecourts
end

这将自动在序列化的json中提供judgecourts关系。经典Post/Comment对象的示例:

Attributes adapter : a post with one comment

2.使用特定格式......

您指定的格式看起来很像JSON:API格式。如果这是您真正想要实现的目标,那么最好使用JSON:API适配器内置ActiveModelSerializer。为此,您需要告诉AMS使用正确的适配器,可能通过初始化文件:

# ./initializers/active_model_serializer.rb
ActiveModelSerializers.config.adapter = :json_api

在此之后,您的json应该按照您期望的方式进行格式化。我不是json api规范的专家,所以可能还有一些东西需要调整。您将能够在ActiveModelSerializers wiki page on adapters, section JSON API中找到有关此适配器的更多信息。

这是我用Post/Comment示例得到的结果:

json_api adapter : a post with one comment

请注意,还有其他专门针对JSON API规范而构建的gem,例如jsonapi-rb和Netflix Fast JSON API。他们可能对你感兴趣。

© www.soinside.com 2019 - 2024. All rights reserved.