次のSQLクエリで、取得したレコードを左外部結合のフィールドで並べ替えようとしています。
@companies = Company.scoped
@companies = @companies.where("companies.is_deleted = 'f' AND companies.state IN (?)", ["draft", "pending"])
@companies = @companies.includes(:events)
@companies = @companies.order("events.created_at DESC")
SELECT "companies"."id" AS t0_r0, "companies"."name" AS t0_r1, "companies"."reference" AS t0_r2, "companies"."state" AS t0_r3, "companies"."description" AS t0_r4, "companies"."remarks" AS t0_r5 "events"."id" AS t2_r0, "events"."eventable_type" AS t2_r1, "events"."eventable_id" AS t2_r2, "events"."event_type" AS t2_r3, "events"."creator_company_id" AS t2_r4, "events"."creator_user_id" AS t2_r5, "events"."created_at" AS t2_r6
FROM "companies"
LEFT OUTER JOIN "events" ON "events"."eventable_id" = "companies"."id" AND "events"."eventable_type" = 'company'
WHERE "companies"."is_deleted" = 'f' AND companies.state IN ('draft','pending')
ORDER BY events.created_at DESC
ただし、取得されたレコードは、期待どおりに正しくソートされていません(つまり、events.created_atによって)
パフォーマンスを効率的に保ちながらそれを成功させる方法の手がかりはありますか?