我正在尝试通过在微博下面创建评论来跟进Michael Hartl的Ruby on Rails教程。我已经创建了一个评论模型,并将其关联为评论belongs_to用户和微博,以及微博has_many评论和用户has_many评论,但是我想知道如何实现这一点。
我会将评论表单呈现给micropost模型吗?
有没有可能有人快速实现这个结构?
发布于 2014-11-03 13:54:51
索引帖子及其评论的示例代码::
在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这只是一个代码示例,用来说明您可以遵循的方法来完成您所要求的操作。
https://stackoverflow.com/questions/26706872
复制相似问题