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 -%>
I'm posting a separate answer since code apparently doesn't format well at all in comments.
I'm guessing the problem you're having with the previous answer is that you're putting
@comments = Comment.find(:all, :order => 'created_at DESC', :limit => 10)
in one of your controller methods. However, you want @comments to be available to a layout file, so you'd have to put that on every controller method for every controller in order for that to work. Although putting logic in views is frowned upon, I think it would be acceptable to do the following in your layout file:
<% Comment.find(:all, :order => 'created_at DESC', :limit => 10).each do |comment| -%>
<p>
<%= comment.text %> on the post <%= comment.post.title %>
</p>
<% end -%>
To get some of the logic out of the view though we can move it into the Comment model
class Comment < ActiveRecord::Base
named_scope :recent, :order => ["created_at DESC"], :limit => 10
Now you can do this in your view:
<% Comment.recent.each do |comment| -%>
<p>
<%= comment.text %> on the post <%= comment.post.title %>
</p>
<% end -%>
This makes for a nice fat model and skinny controller
I tend to use a helper for this:
# 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:
<div id='sidebar'>
<ul id='recent_comments'>
<% sidebar_comments.each do |c| %>
<li class='comment'>
<blockquote cite="<%= comment_path(c) -%>"><%= c.text -%></blockquote>
</li>
<% end %>
</ul>
</div>