2014-11-03 51 views
0

我想通過創建微博下的註釋來跟蹤Michael Hartl的Ruby on Rails教程。 我創建了一個評論模型,並將關聯作爲評論belongs_to user和micropost以及micropost has_many註釋和用戶has_many註釋,但是我想知道如何實現這一點。Ruby on Rails如何創建嵌套註釋

我會將評論表單呈現給微博模型嗎?

有人可以快速實施這種結構嗎?

+0

你能澄清你的意思嵌套評論?你的意思是你想要評論能夠屬於其他評論,所以你可以做回覆評論?因此,它看起來像: ' - 主要的意見1 - 回覆1主評論1 - 回覆2主要的意見1 - 主要的意見2 - 主評論3 ' – Rose 2014-11-03 03:35:16

+0

目前我只想評論屬於微博。 – Jason 2014-11-03 04:09:15

+0

請參閱問題:http://stackoverflow.com/questions/22635981/nested-comments-from-scratch – cweston 2015-10-21 18:32:00

回答

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部分::

%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 

這只是一個代碼示例,用於說明您可以按照您詢問的方式進行操作的方式。

+0

艾哈邁德你可以看看我的另一篇文章?我希望這能更好地展現這一點。 – Jason 2014-11-03 17:45:21