A user can have many posts, and each post can have many comments. When visiting a user’s profile, you get a list of posts rendered like so in the view:
<%= render @posts %>
I want to also render the comments for each post by doing something like:
<%= render @comments %>
However, where would I declare @comments? If I declare it in user#show, then I’d get all the comments for the user, as opposed to the comments for a specific post.
So when a collection is rendered, does it access a controller for each instance? If so, what controller method is it using?
You can render each post’s comments inside the post partial:
This does not go to the controller on each
post.commentsstatement, it just queries the DB.You can also eliminate the multiple queries by setting the @posts instance variable in the controller in the following way:
Then when you do
post.commentsit will not query the DB, but load the comments from the memory.