I want to render a part of embed model's fields.
I wrote bellow code. But, I got a response include all embed model's fields.
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
Sent Request.
GET /races
Gotten response.
[
{
"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"
}
},...
]
I expect the response only include held.held_year
. Expected response is bellow.
[
{
"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
}
},...
]
How Should I fix the code?
I think you can add only:
param to your render
part. Something like this:
render json: Race.includes(:held), include: { held: { only: :held_year } }, status: :ok
Note Race.includes(:held)
to avoid N+1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.