我还没有在Stackoverflow上找到同样的问题。除了医疗辅助队变得如此迅速,甚至2岁的答案经常会过时。ActiveModel :: Serializers JSON API嵌套关联包括?
我使用Rails 5仅API和gem'active_model_serializers'(AMS)(版本0.10.6)。
我也使用JSONAPI响应格式 - 不仅仅是JSON。
我需要渲染一个嵌套包括 - 不仅仅是嵌套关系。
代码例如:
serializer1:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
belongs_to :user
end
serializer2:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :cities
end
serializer3:
class CitySerializer < ActiveModel::Serializer
attributes :id, :name
end
控制器:
def index
@questions = Question.all
render json: @questions, include: [:user, 'user.city']
end
我得到这样的回应:
{
"data": [
{
"id": "1",
"type": "questions",
"attributes": {
"title": "First",
"created-at": "2017-03-27T13:22:15.548Z",
"updated-at": "2017-03-27T13:22:16.463Z"
},
"relationships": {
"user": {
"data": {
"id": "3",
"type": "users"
}
}
}
}
],
"included": [
{
"id": "3",
"type": "users",
"attributes": {
"email": "[email protected]"
},
"relationships": {
"cities": {
"data": [
{
"id": "75",
"type": "cities"
}
]
}
}
}
]
}
我真的得到一个嵌套关系city
。我甚至得到城市id
。
但问题是 - 我怎样才能获得其他city
属性,如name
?我需要另一个include
部分 - 也许在当前include
部分(嵌套?)内。
如何做到这一点? (没有任何额外的宝石)
不,事实并非如此。结果是一样的。 – prograils
您必须设置城市模型 –
某处的属性,除非您允许某些特定属性,否则通常您将获得所有属性 –