Ruby on rails Rails API设计:通过json_API关系包含其他属性的最佳方式
我有一个Rails 5应用程序,在其中我使用gemRuby on rails Rails API设计:通过json_API关系包含其他属性的最佳方式,ruby-on-rails,ruby,api,active-model-serializers,json-api,Ruby On Rails,Ruby,Api,Active Model Serializers,Json Api,我有一个Rails 5应用程序,在其中我使用gem活动的\u model\u序列化程序()。在我的应用程序中,我有一个简化的数据模型,如下所示: # LocalizedString.rb has_many :translations # Translation.rb belongs_to :localized_string ActiveModelSerializers.config.adapter = :json_api 我试图遵循的最佳实践来自,我已将活动\u模型\u序列化器配置为如下所
活动的\u model\u序列化程序
()。在我的应用程序中,我有一个简化的数据模型,如下所示:
# LocalizedString.rb
has_many :translations
# Translation.rb
belongs_to :localized_string
ActiveModelSerializers.config.adapter = :json_api
我试图遵循的最佳实践来自,我已将活动\u模型\u序列化器配置为如下所示:
# LocalizedString.rb
has_many :translations
# Translation.rb
belongs_to :localized_string
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\u api
的最佳/推荐方法是什么
类似这样的方法可能会奏效:
"localized-string": {
"data": {
"id": "162",
"key": "my key value", # the attribute I need.
"type": "localized-strings"
}
}
但我不确定如何使用活动的\u模型\u序列化程序来实现这一点,或者这是否是另一种推荐的方法,我想用[json\u api][1]
来实现这一点
为了完整起见,我的相关serialiser文件如下所示:
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
类TranslationSerializer
那么,我需要做些什么来实现我想要的呢?根据规范,关系由资源对象标识符表示。要包含的不仅仅是id和类型,您需要使用include参数。在AMS中,我认为这应该是“包括:[:localizations],字段:[:localizations:[:key]}”(现在不在计算机上,但大致正确)