# Models
class Cinema < ApplicationRecord
has_many :showtimes
has_many :movies, -> { distinct }, through: :showtimes
end
class Movie < ApplicationRecord
has_many :showtimes
has_many :cinemas, -> { distinct }, through: :showtimes
end
class Showtime < ApplicationRecord
belongs_to :cinema
belongs_to :movie
end
# Controller
class V1::MoviesController < ApplicationController
movie = Movie.find(params[:id])
render json: MovieSerializer.new(movie, include: [..., :cinemas, :'cinemas.showtimes']).serialized_json
end
# Serializers
class MovieSerializer
include FastJsonapi::ObjectSerializer
# Relations
...
has_many :cinemas, serializer: CinemaItemSerializer do |object|
object.cinemas.by_country('FR') #.includes(:showtimes)
end
end
class CinemaItemSerializer
include FastJsonapi::ObjectSerializer
# Relations
has_many :showtimes
end
我使用bullet
gem触发一些n + 1查询,并使用fast_json_api
序列化对象。
当我不使用includes(:showtimes)
时,我有这个响应时间
如您所见,当我不使用includes
时,我的查询会变慢,但总响应时间会变快。
那我应该使用哪一个呢?