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

时间:2018-10-26 18:41:36

标签: ruby-on-rails 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]]`

1 个答案:

答案 0 :(得分:1)

我会将您的if更改为

if appt = @appointments.to_a.first

这将使您的约会通过一个查询无限制地加载到数组中,first将在数组上运行,并且不会对数据库造成额外的查询,然后在呈现所有约会时,它们已经从数据库中获取了。

或者,您的if也可以是

if appt = @appointments[0]