Search code examples
ruby-on-railsrubywill-paginate

Ruby on Rails - Correct way of paginating two lists in one view


So I want to use will_paginate plugin two times on one page. My problem is that when I click next on one of the paginations (@articles pagination), it also goes to the next page on my other pagination (@comments pagination).

<div class="row">
<div class="span6">
  <h3>Posted Articles (<%= @articles.count %>)</h3>
  <ol class="user_articles">
    <% @articles.each do |article| %>
      <li>
        <span class="content"><%= link_to article.title, article.content %></span>
        <span class="timestamp">
        Posted <%= time_ago_in_words(article.created_at) %> ago to <%= article.article_type %>.
        </span>
        <div>
          <% if current_user?(article.user) %>
          <%= link_to "delete", article, method: :delete,
                                 data: { confirm: "You sure?" },
                                 title: article.title %>
          <% end %>
        </div>
      </li>
    <% end %>
  </ol>
  <%= will_paginate @articles %>
</div>

<div class="span6">
<h3>Comments (<%= @comments.count %>)</h3>
  <ol class="user_comments">
    <% @comments.each do |comment| %>
      <li>
        <span class="content"><%= comment.content %></span>
        <span class="timestamp">
        Posted <%= time_ago_in_words(comment.created_at) %> ago to <%= link_to Article.find_by_id(comment.article_id).title, Article.find_by_id(comment.article_id) %>.
        </span>
        <div>
          <% if current_user?(comment.user) %>
          <%= link_to "delete", comment, method: :delete,
                               data: { confirm: "You sure?" },
                                 title: comment.content %>
         <% end %>
        </div>
      </li>
    <% end %>
  </ol>
  <%= will_paginate @comments %>
</div>
</div>

I understand you can specify a :param_name option to tell will_paginate the name of the parameter to use for the page number, but I have no clue what :param_name I should use in order for it to work. Any help would be greatly appreciated!

EDIT:

Here is my user controller for the view:

def show
@user = User.find(params[:id])
@comments = @user.comments.paginate(page: params[:page], :per_page => 20)
@articles = @user.articles.paginate(page: params[:page], :per_page => 20)
end

Solution

  • Your :param_name should be something like :articles_page and :comments_page, specified on each of the pagination statements.