Rails API 设计:包含具有 json_api 关系的其他属性的最佳方式

Rails API Design: best way to include other attributes with json_api relationships

我有一个 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

那么,对于实现我想要的目标我需要做什么有什么想法吗?

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