I have an application with Users, Posts and Comments. Users has_many Posts, Posts has_many Comments and Comments belong_to Users and Posts.
In my view template I’m looping over the Comments like this to get the username of the commenter:
User.find(comment.user_id).name
How efficient is this if I’m doing this for every Comment per Post ?
I could imagine that it’s maybe faster to store the username in a separate row in the Comments table, but duplicating the data seems just wrong.
Am I being paranoid and is ActiveRecord doing some caching magic or is there a better way of doing something like this ?
You can preload the users in the initial query.
Seeing as you have the association setup between User and Comment you can access the user via the association.
Let’s assume you have a controller method:
In your view as you loop over
@comments: