简体   繁体   English

Ruby on Rails如何创建嵌套注释

[英]Ruby on Rails How to Create Nested Comments

I am trying to follow up on Michael Hartl's Ruby on Rails tutorial by creating comments that are under microposts. 我试图通过在微博下创建评论来跟进Michael Hartl的Ruby on Rails教程。 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. 我已经创建了一个Comment模型,并将其关联关系关联为用户和微博的注释属居[subscribe_to]用户以及微博的has_many注释和用户has_many注释,但是我想知道如何实现这一点。

Would I render the comments forms to the micropost model? 我可以将评论表单呈现给微博模型吗?

Is it possible for someone to do a quick implementation of this structure? 有人可以快速实现此结构吗?

Sample code to index posts and their comments :: 索引帖子及其评论的示例代码::

in posts_controller.rb 在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 : 您的代码应采用haml样式:

- @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 :: 在您的_comment.html.haml部分::中

%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. 这只是一个代码示例,用于说明您可以按照自己的方式做所要求的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM