我想通过创建微博下的注释来跟踪Michael Hartl的Ruby on Rails教程。 我创建了一个评论模型,并将关联作为评论belongs_to user和micropost以及micropost has_many注释和用户has_many注释,但是我想知道如何实现这一点。Ruby on Rails如何创建嵌套注释
我会将评论表单呈现给微博模型吗?
有人可以快速实施这种结构吗?
我想通过创建微博下的注释来跟踪Michael Hartl的Ruby on Rails教程。 我创建了一个评论模型,并将关联作为评论belongs_to user和micropost以及micropost has_many注释和用户has_many注释,但是我想知道如何实现这一点。Ruby on Rails如何创建嵌套注释
我会将评论表单呈现给微博模型吗?
有人可以快速实施这种结构吗?
示例代码索引信息及其评论::
在您的视图文件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
这只是一个代码示例,用于说明您可以按照您询问的方式进行操作的方式。
艾哈迈德你可以看看我的另一篇文章?我希望这能更好地展现这一点。 – Jason 2014-11-03 17:45:21
你能澄清你的意思嵌套评论?你的意思是你想要评论能够属于其他评论,所以你可以做回复评论?因此,它看起来像: ' - 主要的意见1 - 回复1主评论1 - 回复2主要的意见1 - 主要的意见2 - 主评论3 ' – Rose 2014-11-03 03:35:16
目前我只想评论属于微博。 – Jason 2014-11-03 04:09:15
请参阅问题:http://stackoverflow.com/questions/22635981/nested-comments-from-scratch – cweston 2015-10-21 18:32:00