Flowdock

Good notes posted by Voyta

RSS feed
August 19, 2008 - (v2.1.0)
8 thanks

preload_associations manually

Usually you preload associations using :include => [ ... ]. In Rails 2.1 each association is fetched with a separate query. Something like:

Post.find(:all, :include => [:tags, :user])

will produce 3 queries - each for posts, tags and users.


But sometimes you have a complex query, which uses :joins => :other_association and conditions between multiple tables, but not the ones you need to include. Then everything is mixed back in one query like in old versions of Rails.

Another case may be when it is not possible to use :include at all, for example while using find_by_sql, but you still want/need to preload associated records.

In rails 2.1 find uses preload_associations internally, when it is possible (There are no joins or conditions between tables).

So then you can preload asociations manually from within your model:

class Post < ActiveRecord::Base

has_many :tags
belongs_to :user
...

def self.find_complex_with_includes
  posts = find_by_sql(...) # or find(:all, :joins => .....)
  preload_associations(posts, [:tags, :user])
  posts
end

end

and then do

@posts = Post.find_complex_with_includes