Rails是否包含真正改进的查询? (带子弹)

时间:2019-01-23 20:17:42

标签: ruby-on-rails ruby postgresql activerecord

# 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)时,我有这个响应时间 enter image description here

如果我确实使用includes,则有此响应时间 enter image description here

如您所见,当我不使用includes时,我的查询会变慢,但总响应时间会变快。

那我应该使用哪一个呢?

0 个答案:

没有答案