I have a model Comment, which has_a User.
In my display page, I am doing a Comment.all, and then displaying each comment.
In the view I need to display not only the comment, but also information about the associated user (ie the author).
<% @comments.each do |comment| %>
<%= comment.user.name %>
<%= comment.user.email %>
...etc...
<% end %>
This is fine and all, but activerecord translates this into one SELECT * FROM users WHERE USER.id = commentId query per EACH comment I have.
This is a little ridiculous, especially on a page with hundreds of comments. (That’s hundreds of individual separate DB hits!)
When I am doing the Comment.all, is there away to tell rails to not only grab the comments, but also grab the associated users, and then when I call comment.user.blah later, for it to not grab it from db again? (This way it would do it all in one db statement).
You should use
.includes.From the doc:
Or, in your case, it would be