/ preloading

Preloading associations while using find_by_sql

To preload the associated records we generally use #includes, #preload or #eager_load for more information please see this blog

This will work perfectly if we preload associations for an ActiveRecord::Relation, but in case if we want to load associated records for an Array, these methods will fail

Let's consider this example

class Company < ActiveRecord::Base
  has_many :users

class User < ActiveRecord::Base
  belongs_to :company

Say we have a query, which is performing joins and also have sub queries, then we would need to use find_by_sql, to generate the query. But find_by_sql will result in array instead of ActiveRecord::Relation

If we try
@users = User.find_by_sql(some_condition).includes(:company)
will throw an error as includes cannot work on an array

If we try calling includes first,
@users = User.includes(:company).find_by_sql(some_conditions)
The includes part is silently dropped and only find_by_sql part gets executed.

So we can let find_by_sql execute first
@users = User.find_by_sql(some_condition)

Then to load associated companies for each user we can use
ActiveRecord::Associations::Preloader.new(@users, :company).run

This will preload the company association for the @users object like it will do when we use includes.

Ruchika Mayekar

Ruby on Rails Developer at Kiprosh, Loves learning new things, reading blogs technical and non-technical.

Read More