views:

281

answers:

1

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

+3  A: 

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.

Andy Gaskell
Thank you so much. That was so much simpler than I was making it.
bgadoci
Sure thing! I added a blurb about string interpolation just in case you haven't seen it before.
Andy Gaskell
That's timely because I was just trying to figure out how to call that count to place anywhere without a link. I appreciate it.
bgadoci
One more request...since you seem to be a rails badass...if you have a second head over to my question at http://stackoverflow.com/questions/1753227/reverse-order-of-display-of-blog-entries-and-comments-ruby-on-rails and look at the top answer and my comment/question about AJAX. If you don't have time I understand. Just thought I would throw it out there as I am trying to hammer through a lot tonight.
bgadoci