Sample code to index posts and their comments ::
in posts_controller.rb
class PostsController < ApplicationController
def index
// **get all posts and eager load their comments just in one database connection**
// if you also needs the owner get it same way here by eager loading.
// Do not write quires in the views.
@posts = Post.all.includes(:comments)
respond_to do |format|
format.html
end
end
end
in your view file if you are going to index comments in somewhere else so make a partial that takes an array of comments and render them or you can do it in only one file but the first is much more clean.
your code should be like that in haml style :
- @posts.each do |post|
// The post it self
%p
= post.content
// whatever data from the post
// loop through the post comments
- post.comments.each do |comment|
// Render the partial of one comment
// this partial should include whatever data or style for your form
// NOTE if your partial in same directory write
= render 'comment', comment: comment
// If it is under comments directory which is better so Write
= render 'comments/comment', comment: comment
// if you need anything from the post also pass it to the form.
in your _comment.html.haml partial ::
%p
= "Content ::" + comment.content
%p
= "Owner name ::" + comment.owner.name
or you can also make your partial loops through the comments and your post view will render it per each post
- @posts.each do |post|
= render 'comments', post: post
in your partial
- post.comments.each do |comment|
%p
= "Content ::" + comment.content
This is just a code example to illustrate the way that you can follow to do what you asked about.