如何在Rails视图中呈现所有注释?

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

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 

如果您想以最近的顺序显示任何post的所有评论,您可以:

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

在视图中你可以做到:

 <% @comments.each do |comment| -%> 

<%= comment.text %> on the post <%= comment.post.title %>

<% end -%>

我发布了一个单独的答案,因为代码显然在评论中根本没有格式化。

我猜你遇到的问题与之前的答案是你正在推杆

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

在你的一个控制器方法中。 但是,您希望@comments可用于布局文件,因此您必须将其放在每个控制器的每个控制器方法上才能使其工作。 尽管在视图中放置逻辑是不受欢迎的,但我认为在布局文件中执行以下操作是可以接受的:

 <% Comment.find(:all, :order => 'created_at DESC', :limit => 10).each do |comment| -%> 

<%= comment.text %> on the post <%= comment.post.title %>

<% end -%>

为了从视图中获取一些逻辑,我们可以将它移到Comment模型中

 class Comment < ActiveRecord::Base named_scope :recent, :order => ["created_at DESC"], :limit => 10 

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

 <% Comment.recent.each do |comment| -%> 

<%= comment.text %> on the post <%= comment.post.title %>

<% end -%>

这使得一个漂亮的胖模型和瘦的控制器

我倾向于使用帮助器:

 # in app/helpers/application_helper.rb: def sidebar_comments(force_refresh = false) @sidebar_comments = nil if force_refresh @sidebar_comments ||= Comment.find(:all, :order => 'created_at DESC', :limit => 10) # or ||= Comment.recent.limited(10) if you are using nifty named scopes end # in app/views/layouts/application.html.erb: