开发者

Count records for Blog in Ruby on Rails - Easy Question

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 %>
开发者_如何学JAVA

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).


Get rid of that controller method - replacing your current link_to for example:

<%= link_to "View & Add Comments (#{post.comments.count})" %>

If you already have the @post object to get the number of comments you just need to call comments.count. And if you are unfamiliar with string interpolation, this link might help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜