我還沒有在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
您必須設置城市模型 –
某處的屬性,除非您允許某些特定屬性,否則通常您將獲得所有屬性 –