Search code examples
sqlruby-on-railsactiverecordeager-loadingmodel-associations

ActiveRecord - How to join association with pure SQL query


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.


Solution

  • 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.