首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby on Rails如何创建嵌套注释

Ruby on Rails如何创建嵌套注释
EN

Stack Overflow用户
提问于 2014-11-03 10:17:59
回答 1查看 732关注 0票数 0

我正在尝试通过在微博下面创建评论来跟进Michael Hartl的Ruby on Rails教程。我已经创建了一个评论模型,并将其关联为评论belongs_to用户和微博,以及微博has_many评论和用户has_many评论,但是我想知道如何实现这一点。

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

有没有可能有人快速实现这个结构?

EN

回答 1

Stack Overflow用户

发布于 2014-11-03 13:54:51

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

在posts_controller.rb中

代码语言:javascript
复制
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风格的那样:

代码语言:javascript
复制
- @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中::

代码语言:javascript
复制
%p
  = "Content ::" + comment.content
%p
  = "Owner name ::" +  comment.owner.name

或者你也可以在评论中进行部分循环,你的帖子视图将为每个帖子呈现它

代码语言:javascript
复制
- @posts.each do |post|
  = render 'comments', post: post

在你的部分

代码语言:javascript
复制
- post.comments.each do |comment|
  %p
    = "Content ::" + comment.content

这只是一个代码示例,用来说明您可以遵循的方法来完成您所要求的操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26706872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档