如何在 Rails 视图中呈现所有评论?
我是 Rails 新手,所以放轻松。我创建了一个博客。我已成功实施评论并将其附加到每个帖子中。现在...我想在侧边栏中显示所有帖子的最新评论列表。我认为这里涉及两件事,对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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想按最近的顺序显示任何帖子中的所有评论,您可以执行以下操作:
在视图中您可以执行以下操作:
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:
我正在发布一个单独的答案,因为代码显然在注释中根本没有很好的格式。
我猜您之前的答案遇到的问题是您放入
了一种控制器方法。但是,您希望 @comments 可用于布局文件,因此您必须将其放在每个控制器的每个控制器方法上才能使其正常工作。尽管将逻辑放入视图中是不受欢迎的,但我认为在布局文件中执行以下操作是可以接受的:
尽管我们可以将某些逻辑移出视图,但我们可以将其移至注释模型中
现在您可以在布局文件中执行此操作视图:
这使得胖模型和瘦控制器
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: