Hello,
I was wondering if there is an easy way to handle this N+1 problem.
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
def full_name
“comment on #{post.title} by #{author}”
end
end
Now when I want a post with all its comments, I go:
p=Post.find(:first, :include => :comments)
queries:
Post Load Including Associations (0.000863) SELECT posts.“id” AS
t0_r0, posts.“title” AS t0_r1, posts.“body” AS t0_r2, posts.“eated_at”
AS t0_r3, posts.“updated_at” AS t0_r4, comments.“id” AS t1_r0,
comments.“post_id” AS t1_r1, comments.“body” AS t1_r2,
coents.“created_at” AS t1_r3, comments.“updated_at” AS t1_r4 FROM
posts LEFT OUTER JOIN comments ON comments.post_id = posts.id
p.comments.first.full_name
queries:
Post Load (0.000650) SELECT * FROM posts WHERE (posts.“id” = 1)
It seems to me it’s a little dumb to re-get the post, since it’s
already loaded and associated to this comment(since the comment was
loaded through the post’s association).
Ofcourse I could use Post.find(:first, :include => {:comments
=> :post}).
But it doesn’t feel right since Post is included twice.
Any “good” way to do this?
Thanks.
Mathijs