优化ActiveRecord查询.是否可以将两个查询合并为一个查询



优化ActiveRecord查询。是否可以将两个查询合并为一个查询?

我需要得到所有的记录,以及我使用的第一张记录。

@appointments ||= @lead.appointments.order(created_at: :desc)
if appt = @appointments.first
json.latest_appointment do
json.partial! 'api/v1/lead_appointments/appointment', appointment: appt
end
end
json.appointments do
json.array! @appointments do |a|
json.partial! 'api/v1/lead_appointments/appointment', appointment: a
end
end

并获得类似的sql查询

Appointment Load (0.4ms)  SELECT  "appointments".* FROM "appointments" WHERE "appointments"."lead_id" = $1 ORDER BY "appointments"."created_at" DESC LIMIT $2  [["lead_id", 760730], ["LIMIT", 1]]`
Appointment Load (0.4ms)  SELECT  "appointments".* FROM "appointments" WHERE "appointments"."lead_id" = $1 ORDER BY "appointments"."appointment_at" DESC  [["lead_id", 760730]]`

我会将您的if更改为

if appt = @appointments.to_a.first

这将导致您的约会无限制地加载到具有一个查询的数组中,first将在数组上工作,而不会对数据库产生额外的查询,然后当您呈现所有约会时,它们已经从数据库中提取。

或者,您的if也可以是

if appt = @appointments[0]

最新更新