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
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
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:
To get some of the logic out of the view though we can move it into the Comment model
Now you can do this in your view:
This makes for a nice fat model and skinny controller
I tend to use a helper for this:
If you want to display all the comments from any post, in most recent order, you could do:
And in the view you can do: