0

I'm doing the following query:

TaskCheck.find_by_sql ["SELECT task_checks.*, tasks.* FROM task_checks INNER JOIN tasks ON task_checks.task_id = tasks.id"]

It returns TaskCheck objects but when I try to read a Task field(joined in the query) then ActiveRecord does a separate select query for each object. It's lazy loading my association even if I'm joining it. How do I fix that?

PS: I want to use pure SQL. The reason is because AR "includes" method executes a second SELECT for the association which is inneficient for a one-to-one association and I want the best perfomance possible.

Jirico
  • 1,242
  • 1
  • 15
  • 29
  • This is so simple if you don't use pure SQL. Why use pure sql? – Jesse Wolgamott Apr 26 '13 at 21:22
  • 1
    Because this part of the system will be executed thousand of times a day and I want the best perfomance possible. – Jirico Apr 29 '13 at 12:36
  • And I remember now, the main reason is because AR "includes" method does a separate SELECT for the association. That is a good approach for Rails and a one-to-many association, but not effective in a one-to-one association. – Jirico Apr 29 '13 at 12:43

1 Answers1

0

There is a way where u can specify the columns you want, like this:

sql = "SELECT task_checks.*, tasks.* FROM task_checks INNER JOIN tasks ON task_checks.task_id = tasks.id"
records_array = ActiveRecord::Base.connection.execute(sql)

Then, records_array will contain all returning rows with the specified columns in the select query.

Jirico
  • 1,242
  • 1
  • 15
  • 29