# 2-way associations

**URL:** <https://www.ruby-forum.com/t/2-way-associations/130150>\
**Category:** Rails\
**Created:** [February 25, 2008, 9:19pm UTC](https://www.ruby-forum.com/t/2-way-associations/130150 "2008-02-25T21:19:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [February 25, 2008, 9:19pm UTC](https://www.ruby-forum.com/t/2-way-associations/130150/1 "2008-02-25T21:19:05Z")

</div>

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
