0
votes

I am trying to follow up on Michael Hartl's Ruby on Rails tutorial by creating comments that are under microposts. I have created a Comment model and have the association as comment belongs_to user and micropost as well as microposts has_many comments and user has_many comments, however I am wondering how to implement this.

Would I render the comments forms to the micropost model?

Is it possible for someone to do a quick implementation of this structure?

1
Can you clarify what you mean by nested comments? Do you mean you want comments to be able to belong to other comments so you can do reply comments? So it would look like: ` - Main comment 1 -- Reply 1 to main comment 1 -- Reply 2 to main comment 1 - Main comment 2 - Main comment 3 ` - Rose
Currently I just want comments that belong to microposts. - Jason

1 Answers

0
votes

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.