Ruby on Rails如何创建嵌套注释

时间:2014-11-03 02:17:59

标签: ruby-on-rails ruby-on-rails-4 railstutorial.org

我正在尝试通过创建微博的评论来跟进Michael Hartl的Ruby on Rails教程。 我创建了一个Comment模型,并将关联作为注释belongs_to user和micropost以及microposts has_many注释和用户has_many注释,但是我想知道如何实现它。

我会将评论表单呈现给微博模型吗?

有人可以快速实施这种结构吗?

1 个答案:

答案 0 :(得分:0)

索引帖子及其评论的示例代码::

在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

在你的视图文件中,如果你要在其他地方索引注释,那么制作一个注释数组的部分并渲染它们,或者你只能在一个文件中执行它,但第一个更干净。

你的代码应该像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.
你的_comment.html.haml partial ::

中的

%p
  = "Content ::" + comment.content
%p
  = "Owner name ::" +  comment.owner.name

或者你也可以通过评论进行部分循环,你的帖子视图将按照每个帖子进行渲染

- @posts.each do |post|
  = render 'comments', post: post

在您的部分

- post.comments.each do |comment|
  %p
    = "Content ::" + comment.content

这只是一个代码示例,用于说明您可以按照所要求的方式进行操作。