Liam
Liam

Reputation: 43

How to display all posts with all its comments - Ruby on Rails

I'm new to rails and don't know how to achieve this in rails. It might be a really stupid question. But it was not covered in the RoR Codecademy course I did and could not fint a answer elsewhere.

So I have two tables, posts and comments that have an one-to-many relationship. One post has many comments.

I want to display all post with all its comments underneath. What would be the correct way to do this?

Upvotes: 2

Views: 3791

Answers (2)

Gaurav Gupta
Gaurav Gupta

Reputation: 1191

There are two ways to do this:

First: you can do like this way in your post controller action (suppose :index) do:

def index
  @posts = Post.all
end

And in your index.html.erb

<% @posts.each do |post|%>
  # Your post attribute like name etc
  <% post.comments.each do |comment|%>
    # Your post attribute like name etc
  <% end %>
<% end %>    

Second: in your post controller action do:

 def index
   @posts = Post.all.includes(:comments)
 end

And in your index.html.erb

<% @posts.each do |post|%>
  # Your post attribute like name etc
  <% post.comments.each do |comment|%>
    # Your post attribute like name etc
  <% end %>
<% end %>    

Difference in above two ways is that in first one there is always a data base call when you do "post.comments" but in second there is only two data base call i.e. "Post.all.includes(:comments)", no data base call at view part, so it is up to you which way you want to use.

Upvotes: 4

infused
infused

Reputation: 24337

If a Post has_many comments then:

post = Post.find(1)
post.comments.each do |comment|
  # do something with each comment here
end

Upvotes: 0

Related Questions