如何在Rails视图中呈现所有注释? [英] How do I render all Comments in a Rails view?

查看:84
本文介绍了如何在Rails视图中呈现所有注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Rails的新手,所以轻松一点.我已经创建了一个博客.我已经成功实施了评论,并将其附加到每个帖子中.现在...我想在侧栏中显示所有帖子中的最新评论列表.我认为这里涉及两件事,一个是对comment_controller.rb的更新,然后是来自实际页面的调用.这是注释控制器代码.

I am new to rails so go easy. I have created a blog. I have successfully implemented comments and attached them to each post. Now...I would like to display, in the sidebar, a list of the most recent comments from across all posts. I think there are two things involved here, an update to the comment_controller.rb, and then the call from the actual page. Here is the comments controller code.

class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create!(params[:comment])

    respond_to do |format|
      format.html { redirect_to @post}
      format.js
    end
  end
end

推荐答案

如果要以最新顺序显示任何帖子中的所有评论,则可以执行以下操作:

If you want to display all the comments from any post, in most recent order, you could do:

@comments = Comment.find(:all, :order => 'created_at DESC', :limit => 10)

在视图中,您可以执行以下操作:

And in the view you can do:

<% @comments.each do |comment| -%>
    <p>
        <%= comment.text %> on the post <%= comment.post.title %>
    </p>
<% end -%>

这篇关于如何在Rails视图中呈现所有注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆