How do i display comments count of next page?
I have a post and post has many comments, and i have made a load more button to load more comments with ajax.
I would like to display on the button how many comments next page has.
I use will_paginate
To display the comments count of the next page on gorails.com, you need to use some Ruby code to calculate the total number of comments for each post and then paginate them using will_paginate. You can also use a helper method to display the pagination links with the count information.
One possible solution is to use the total_entries option of will_paginate to pass the total number of comments for each post. You can get this number by calling count on the comments association of the post. For example, in your controller, you can do something like this:
@post = Post.find(params[:id])
@comments = @post.comments.paginate(page: params[:page], per_page: 10, total_entries: @post.comments.count)
Then, in your view, you can use a helper method to display the pagination links with the count information. For example, you can define a method like this in your application_helper.rb file:
def pagination_with_count(collection)
content_tag(:div, class: "pagination") do
will_paginate(collection) +
content_tag(:span, "Showing #{collection.offset + 1}-#{collection.offset + collection.length} of #{collection.total_entries} comments", class: "count")
end
end
Then, in your view, you can call this method like this:
<%= pagination_with_count(@comments) %>
This will display something like this:
< Prev 1 2 3 Next > Showing 11-20 of 25 comments
Many thanks for providing this guide! The pagination links with the count information can be shown by using a helper method