While I’m happy to continue talking about the vagaries of Rails
also need to actually build apps.
I may have discovered a bit of a problem with :include as it applies to
associations. First, let me say that I’m a big fan of :include for
number of SQL calls. There are times when I wish it could go more than 1
away from the parent object, but I kind of understand why it can’t. Now,
Completely contrived example follows:
I have the following Models:
class Author < ActiveRecord::Base
class Post < ActiveRecord::Base
class Category < ActiveRecord::Base
There are many authors in the database that no posts, and there are
posts in the database that have no category.
If I do:
@authors = Author.find(:all, :include => :posts)
Every entry in the @authors array will have a posts list attached to it.
list will be empty if there are no posts for that author, which is great
handling associated posts in a view.
However, if I do:
@posts = Post.find(:all, :include => :category)
We actually see something different (and I think, inconsistent). Only
objects that have an associated category will have a category entry in
hash. Those without, don’t have a category entry.
Sorry for the length… here’s my actual question.
Why doesn’t :include result in an empty object in those posts without an
associated category record? If I loop over @posts and make a call to:
ActiveRecord ends up making additional SQL calls for every case where
statement evals to true. Why doesn’t the :include “work” for these
OK, so I really had 2 questions…