如何在rails 4.2.5中使用分页并且还能够使用ajax重新排序列表?

时间:2016-01-07 14:34:31

标签: ruby-on-rails ajax pagination kaminari

我正在使用Rails v 4.2.5中的论坛类型的应用程序。我的索引页面是应用程序中讨论的所有问题的列表,它们默认按created_at日期排序。我也使用Kaminari宝石来分页所有问题(每页25个)。我原来的应用程序设置如下:

问题主持人:

def index
  @questions = Question.order(:created_at).page params[:page]
end

索引视图:

# I render a partial that iterates through the questions list to display 
# the title of the questions, then I include the paginate code below.

<div class="pagination">
  <%= paginate @questions  %>
</div>

我最终决定我希望用户能够按照不同的标准对问题进行排序(例如,通过总投票数量,问题的答案总数以及最近提出的问题)。现在,您可以单击与所需排序类型对应的链接,并将新的排序列表(部分)AJAX到页面上。但是,当我这样做时,分页不起作用,当我点击查看结果的第二页时,一切都变得未分类。

带排序链接的索引视图:

<div class="sort_selection">
  <h3> Sort By: </h3>
    <%= link_to "By Upvotes", "/questions/top?sort=votes", class:     "question_sort_link" %>
    <%= link_to "Answers Provided", "/questions/top?sort=answers", class: "question_sort_link" %>
    <%= link_to "Recently Asked", "/questions/top?sort=recent", class:     "question_sort_link" %>
</div>

索引控制器:

def top
    case params[:sort]
    when "votes"
      @questions = Question.sort_by_votes #sort_by_votes is a method in my Question model that performs a SQL query
    when "answers"
      @questions = Question.where.not(answers_count: nil).order(answers_count: :desc).limit(25)
    when "recent"
      @questions = Question.order(created_at: :desc).limit(25)
    end
    render partial: 'questions_list', layout: false
end

Javascript AJAX

$(document).on("click", ".question_sort_link", function(event){
event.preventDefault();
  $.ajax({
    method: "get",
    url: $(this).attr("href")
  }).done(function(sorted){
    $('.questions_show_sorted').replaceWith(sorted);
  });
});

我在视图中放置了<%= paginate @questions %>,并删除了我的控制器中的25限制,并在Top路线中的所有查询后添加了.page params[:page],但我仍然不能在我将AJAX排序到页面上之后,让分页工作。有没有人有什么建议?

2 个答案:

答案 0 :(得分:0)

当您切换页面时,有关排序的数据会丢失,因为您正在使用不同的参数重新加载网站。你可以尝试将这些数据(你要排序的列,信息是asc或desc)传递给新页面,并在加载之前对其进行排序,或者使用AJAX对其进行分页(但这意味着首先加载所有内容)加载)。我不能告诉分页不起作用的问题&#34;,因为我不知道你的意思。

一般来说,你要做的事情相当复杂,并没有简单的解决方案。有一个名为Datatables的JS库,(理论上)使它更容易。还有另一个名为jQ-Bootgrid的库,以及一个名为&#34; Smart listing&#34;的红宝石宝石。

答案 1 :(得分:0)

我认为您需要在ajax响应中提供分页链接,并将其替换为您的JavaScript回调。 我假设您返回的是html而不是json,这会使它有点尴尬。也许您可以使用分页链接和html内容构建json响应

{
  next: /list?page=3,
  prev: /list?page=1,
  content: "<ul>
             <li>foo</li>
             <li>bar</li>
            </ul>"
}