【发布时间】: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);
});
});
我愚弄了<%= paginate @questions %> 在视图中的位置,并在我的控制器中删除了 25 个限制,并在 Top 路由中的所有查询之后添加了.page params[:page],但我仍然无法获得分页在我将 AJAX 排序列表添加到页面上之后工作。有没有人有什么建议?
【问题讨论】:
-
你的 question_list 部分是什么样的?您肯定需要在控制器中的 @questions 数组上调用 .page params[:page] 才能使其工作。
-
当您获得新的排序顺序时,您需要替换分页助手。
标签: ruby-on-rails ajax pagination kaminari