我在我的rails应用程序中使用kaminari gem进行分页以对类别进行分页。 我已经实现了所有过程,并且还显示了分页链接。但这不会影响表格元素列表。
控制器中的索引操作
def index
@categories = current_user.categories
@categories = Kaminari.paginate_array(@categories).page(params[:page]).per(5)
end
索引视图
<h1>Categories</h1>
<div class="well">
<%= link_to "+ New Category", new_category_path, class: "btn btn-success" %>
</div>
<%= paginate @categories %>
</br>
<%= page_entries_info @categories %>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% if current_user.categories.count == 0 %>
<tr>
<td colspan="2">
No categories found. Click the button above to add a new one.
</td>
</tr>
<% else %>
<% current_user.categories.each do |category| %>
<tr>
<td><%= link_to category.name, category %></td>
<td><%= link_to "Edit", edit_category_path(category), class: "btn btn-primary" %>
<%= link_to "Delete", category, method: :delete,
data: { confirm: "You sure?" }, class: 'btn btn-small btn-danger' %>
</td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
如上图所示,它显示了5页/页分页的所有7个条目。
有人可以解释一下它无法正常工作的原因。
答案 0 :(得分:2)
我认为问题在于你的数组类型。请尝试以下代码。
def index
@categories = current_user.categories.all
unless @categories.kind_of?(Array)
@categories = @categories.page(params[:page]).per(5)
else
@categories = Kaminari.paginate_array(@categories).page(params[:page]).per(5)
end
end
你试过这种方式吗?它更加优化,只获取那些所需的记录。
@categories = current_user.categories.page(params[:page]).per(5)