ActiveRecords在执行之前总是运行SELECT COUNT(*)语句

时间:2018-01-02 05:55:08

标签: ruby-on-rails activerecord

我有以下型号:

class Batch < ApplicationRecord
  belongs_to :deliverer, optional: true
  has_many :stops, dependent: :destroy
end

class Task < ApplicationRecord
  belongs_to :job, dependent: :destroy
  belongs_to :stop, optional: true
end

class Stop < ApplicationRecord
  belongs_to :batch
  has_many :tasks
end

class Job < ApplicationRecord
  has_many :tasks
end

我正在进行连接查询以获取所有不同的工作:

batch.stops.joins(tasks: :job).select('distinct on (jobs.id) jobs.*')

但不知何故,在运行实际的sql语句之前,查询总是运行SELECT COUNT(*)语句:

   (5.0ms)  SELECT COUNT(*) FROM "stops" INNER JOIN "tasks" ON "tasks"."stop_id" = "stops"."id" INNER JOIN "jobs" ON "jobs"."id" = "tasks"."job_id" WHERE "stops"."batch_id" = $1  [["batch_id", 1]]
  Stop Load (3.0ms)  SELECT distinct on (jobs.id) jobs.* FROM "stops" INNER JOIN "tasks" ON "tasks"."stop_id" = "stops"."id" INNER JOIN "jobs" ON "jobs"."id" = "tasks"."job_id" WHERE "stops"."batch_id" = $1  [["batch_id", 1]]

想知道这是否是预期的行为,或者这是一个可以防止的不必要的陈述。

3 个答案:

答案 0 :(得分:0)

distinct_jobs_ids =  batch.stops.joins(tasks: :job).distinct.pluck(:'jobs.id')

distinct_jobs = Job.where(id: distinct_jobs_ids)

另一种方法: -

distinct_jobs = distinct_jobs_ids =  batch.stops.joins(tasks: :job).select('distinct jobs')

答案 1 :(得分:0)

试试这个:

batch.stops.joins(tasks: :job).distinct.select(jobs.id)

batch.stops.joins(tasks: :job).distinct.collect(jobs.id)

答案 2 :(得分:0)

您可以尝试以下方法吗?

class Batch < ApplicationRecord
  belongs_to :deliverer, optional: true
  has_many :stops, dependent: :destroy
  # insert the following
  has_many :jobs, through: :stops
end

class Stop < ApplicationRecord
  belongs_to :batch
  has_many :tasks
  # insert the following
  has_many :jobs, through: :tasks, source: :job
end

用法

batch.jobs.distinct