Simple activerecord relationship question

Hey guys, I have a really simple question about activerecord

Lets say I have a Post model which has a has_many relationship with a comments model. (a post is a blog post with many comments)

So, when I execute this

@posts = Post.find(:all)

does every post object in @posts contain all the comment objects for that post?

I know if I do a post.comments I will find them there... but I just want to know what goes on when I bring all the posts or a single post, if the post object will be created with every single related comment object that will take a lot of memory every time I instance one

or are the comment objects instanced when I do a .comments and not before?

They're only instanced, when you access them with @post.comments

But you can eager load them with @posts = Post.find(:all, :include => [:comments]) for better performance, if you know you'll use them anyway

In this case it would get them with an INNER JOIN

btw: You can see the generated SQL in development.log

thanks for your reply thorsten,

So I don't have to worry whenever I find a post that it will bring along with it hundreds of comment objects? only whenever I try to access them they are queried and instanced?

Yep, take te most simple case @post = Post.find(123) your SQL for the normal find will look like: SELECT ALL * FROM posts WHERE id=123; (in principle, the ALL * is a bit more complicated for Rails internals, but not making it slower) In this case a @posts.comments.each do |comment|    ...do something with them here... end

will give you another query like SELECT ALL * FROM comments WHERE post_id=123;

But only once i think, if you access comments later in code again, Rails knows, that it's already in memory

If you use include @post = Post.find(123, :include => [:comments])

the SQL would look like SELECT ALL * FROM posts INNER JOIN comments ON post.id=comments.post_id which is of course more efficient if you will use them anyway

Thanks! I had my activerecord basics all wrong, this really helps a lot