【问题标题】:How to use pagination in rails 4.2.5 and also have the ability to reorder the list with ajax?如何在 rails 4.2.5 中使用分页并且还能够使用 ajax 重新排序列表?
【发布时间】:2016-01-07 14:34:30
【问题描述】:

我正在使用 Rails v 4.2.5 开发一个论坛类型的应用程序。我的索引页面是应用程序中正在讨论的所有问题的列表,它们默认按 created_at 日期排序。我还使用 Kaminari gem 对所有问题进行分页(每页 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);
  });
});

我愚弄了&lt;%= paginate @questions %&gt; 在视图中的位置,并在我的控制器中删除了 25 个限制,并在 Top 路由中的所有查询之后添加了.page params[:page],但我仍然无法获得分页在我将 AJAX 排序列表添加到页面上之后工作。有没有人有什么建议?

【问题讨论】:

  • 你的 question_list 部分是什么样的?您肯定需要在控制器中的 @questions 数组上调用 .page params[:page] 才能使其工作。
  • 当您获得新的排序顺序时,您需要替换分页助手。

标签: ruby-on-rails ajax pagination kaminari


【解决方案1】:

当您切换页面时,有关排序的数据会丢失,因为您正在使用不同的参数重新加载站点。您可以尝试将此数据(您要排序的列,信息是 asc 还是 desc)传递到新页面,并在加载之前对其进行排序,或者使用 AJAX 对其进行分页(但这意味着首先加载所有内容加载)。我无法说出“分页不起作用的问题”,因为我不知道您的意思。

一般来说,您尝试做的这件事相当复杂,并且没有简单的解决方案。有一个名为 Datatables 的 JS 库(理论上)它更容易。还有另一个名为 jQ-Bootgrid 的库,以及一个名为“智能列表”的 ruby​​ gem。

【讨论】:

    【解决方案2】:

    我认为您需要在 ajax 响应中提供分页链接,并在您的 javascript 回调中替换它们。 我假设您返回的是 html 而不是 json,这会让这有点尴尬。也许你可以建立一个带有分页链接和 html 内容的 json 响应

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2013-05-04
      相关资源
      最近更新 更多