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


i'm new rails , don't know how achieve in rails. might stupid question. not covered in ror codecademy course did , not fint answer elsewhere.

so have 2 tables, posts , comments have one-to-many relationship. 1 post has many comments.

i want display post comments underneath. correct way this?

there 2 ways this:

first: can way in post controller action (suppose :index) do:

def index   @posts = post.all end 

and in index.html.erb

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

second: in post controller action do:

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

and in index.html.erb

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

difference in above 2 ways in first 1 there data base call when "post.comments" in second there 2 data base call i.e. "post.all.includes(:comments)", no data base call @ view part, way want use.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -