[英]How to render a part of fields embed model?
我想渲染嵌入模型字段的一部分。
我寫了下面的代碼。 但是,我得到的回復包括所有嵌入模型的字段。
class RacesController < ApplicationController
def index
render json: Race.all, include: 'held.held_year', status: :ok
end
end
class RaceSerializer < ActiveModel::Serializer
attributes :id, :held_id, :course_id, :race_round, :name, :created_at, :updated_at
belongs_to :held
end
class HeldSerializer < ActiveModel::Serializer
attributes :id, :racecourse_id, :held_year, :held_month, :held_day,
:number_of_times, :number_of_days, :created_at, :updated_at
has_many :races
end
發送請求。
GET /races
得到回應。
[
{
"id": 7,
"held_id": 1,
"course_id": 2,
"race_round": 7,
"name": "3歳1勝クラス",
"created_at": "2022-04-13T07:49:30.000Z",
"updated_at": "2022-04-13T07:49:30.000Z",
"held": {
"id": 1,
"racecourse_id": 6,
"held_year": 22,
"held_month": 4,
"held_day": 9,
"number_of_times": 3,
"number_of_days": 5,
"created_at": "2022-04-13T07:49:30.000Z",
"updated_at": "2022-04-13T07:49:30.000Z"
}
},...
]
我希望響應僅包括held.held_year
。 預期的響應如下。
[
{
"id": 7,
"held_id": 1,
"course_id": 2,
"race_round": 7,
"name": "3歳1勝クラス",
"created_at": "2022-04-13T07:49:30.000Z",
"updated_at": "2022-04-13T07:49:30.000Z",
"held": {
"held_year": 22
}
},...
]
我應該如何修復代碼?
我認為你只能添加only:
參數到你的render
部分。 是這樣的:
render json: Race.includes(:held), include: { held: { only: :held_year } }, status: :ok
注意Race.includes(:held)
以避免 N+1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.