在 Ruby on Rails 中计算博客记录 - 简单问题
我是 Rails 新手,很抱歉问这个简单的问题。我已经遵循了几个教程并建立了一个带有评论的博客(甚至使用了一点 AJAX - 哈为自己感到骄傲)。我已经完成了一些自定义,现在我正在尝试在 index.html.erb 中显示评论计数,该评论计数是一个可点击的链接,可将您带到 show.html.erb 页面。这是我到目前为止所做的,不确定它是否正确。在 comments_controller 中,我添加了以下内容:
def count
@post = Post.find(params[:post_id])
@comment = @post.comments.count(params[:comment])
end
第一个问题是,这是计算与特定帖子相关的评论的正确定义。第二个问题是我如何在我的 index.html.erb 页面中调用它,其中有以下内容:
<% @posts.each do |post| %>
<%= render :partial => post %>
<%= link_to 'View & Add Comments', post %>
<% end %>
如您所见,我当前正在使用 link_to 引用来访问该页面,但理想情况下希望它显示类似以下内容: (8)。
I am new to rails so sorry for the simple question. I have followed several tutorials and set up a blog with comments (even using a little AJAX - Ha proud of myself). I have done some customizing and right now I am trying to display in the index.html.erb a comment count that is a clickable link that takes to you the show.html.erb page. Here is what I did so far and not sure it is right. In the comments_controller I have added the following:
def count
@post = Post.find(params[:post_id])
@comment = @post.comments.count(params[:comment])
end
First question is this the correct def to count comments associated with a particular post. Second question is how do I then call it in my index.html.erb page where I have the following:
<% @posts.each do |post| %>
<%= render :partial => post %>
<%= link_to 'View & Add Comments', post %>
<% end %>
As you can see I am currently using a link_to reference to get to the page but ideally would like it to show something like: Comments (8).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
摆脱该控制器方法 - 替换当前的 link_to 例如:
如果您已经拥有
@post
对象来获取评论数量,则只需调用comments.count
。如果您不熟悉字符串插值,此链接 可能有帮助。Get rid of that controller method - replacing your current link_to for example:
If you already have the
@post
object to get the number of comments you just need to callcomments.count
. And if you are unfamiliar with string interpolation, this link might help.