【问题标题】:Rails API Design: best way to include other attributes with json_api relationshipsRails API 设计:使用 json_api 关系包含其他属性的最佳方式
【发布时间】:2016-11-04 20:26:39
【问题描述】:

我有一个 Rails 5 应用程序,我在其中使用 gem active_model_serializers(https://github.com/rails-api/active_model_serializers)。在我的应用中,我有一个简化的数据模型,看起来像这样:

# LocalizedString.rb
has_many :translations

# Translation.rb
belongs_to :localized_string

我正在尝试遵循 JSON API 的最佳实践,我已经像这样配置了 active_model_serializers

ActiveModelSerializers.config.adapter = :json_api

当 API 的用户请求翻译时 (http://[root]/api/apps/117/translations),我目前得到以下结果:

{
  "data": [
    {
      "id": "152",
      "type": "translations",
      "attributes": {
        "value": "Test",
      },
      "relationships": {
        "language": {
          "data": {
            "id": "1",
            "type": "languages"
          }
        },
        "localized-string": {
          "data": {
            "id": "162",
            "type": "localized-strings"
          }
        }
      }
    },
    [...]

在我的localised-string 中,我还想包含另一个对 API 的使用者至关重要的属性,并且我不想进行另一个 API 调用来获取该属性的值。我想知道如果可能的话,最好/推荐的方法是什么,也遵循json_api

这样的事情可能会起作用:

"localized-string": {
  "data": {
    "id": "162",
    "key": "my key value", # the attribute I need.
    "type": "localized-strings"
  }
}

但我不确定如何使用active_model_serializers 来实现这一点,或者是否是另一种推荐的使用[json_api][1] 做我想做的事情的方法。

为了完成,我的相关序列化程序文件如下所示:

class TranslationSerializer < ActiveModel::Serializer
  attributes :id, :value, :created_at, :updated_at

  has_one :language
  has_one :localized_string, serializer: LocalizedStringParentSerializer
end

class LocalizedStringParentSerializer < ActiveModel::Serializer
  # I want to include the key attribute in my relationship object, but this doesn't work. 
  attributes :id, :key
end

那么,对于我需要做什么来实现我想要的东西有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby api active-model-serializers json-api


    【解决方案1】:

    根据规范,关系由资源对象标识符表示。要包含的不仅仅是 id 和类型,您需要使用 include 参数。在 AMS 中,我认为这将是 'include: [:localizations], fields: {localizations: [:key]}'(现在不在计算机上,但大致正确)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多