问题描述
所以我列出了我网站的所有成员并按名称对他们进行分组,以便更好地组织列表.因此,在我看来,我的所有成员都按其成员名称的第一个字母进行分组,例如:
B烤鱼啤酒丹Bigmike33xC愤世嫉俗的刺客等..
无论如何,我也想对这个列表进行分页,但如果我使用 order,我就无法将 Kaminari 的分页参数添加到我的控制器中,因为我遇到了未定义的方法错误.
所以这不起作用:
@members = Member.all.group_by{|u|u.fullname[0].titleize}.page(params[:page]).per(18)
我的观点是这样的:
<% @members.keys.sort.each 做 |starting_letter|%><h3><%= link_tostarting_letter, {:action =>:browse, :controller =>:members, :letter =>起始字母 } %><ol><% @members[starting_letter].each do |member|%><li><% if member.is_artist?%><%= link_to member.full_name, member_path(member), :class=>艺术家"%><%其他%><%= link_to member.full_name, member_path(member) %><%结束%><%结束%></ol><%结束%>
这是我的错误信息:
NoMethodError(# 的未定义方法`page'):app/controllers/members_controller.rb:10:in `index'
Kaminari 将 page
方法添加到 ActiveRecord::Relation
但Member.all.group_by
返回哈希值.这就是您收到此异常的原因.
我建议在分页后进行分组,例如:
@members = Member.order(:full_name).page(params[:page]).per(18).to_a.group_by { |u|u.fullname[0].upcase }
更新
为了使用 paginate
助手,您可以分配 2 个变量,例如:
@paginated_members = Member.order(:full_name).page(params[:page]).per(18)@members = @paginated_members.to_a.group_by { |u|u.fullname[0].upcase }
并将 @paginated_members
传递给 paginate
助手.
So Im listing out all the members of my site and grouping them by name so that the list will be organized better. So in my view all my members are grouped by the first letter of their member name like:
B
Bakedfish
Beercan Dan
Bigmike33x
C
Cynicalassassin
ect..
Anyway, I also want to paginate this list but I cant add Kaminari's pagination arguments to my controller if Im using order because I get an undefined method error.
so this doesnt work:
@members = Member.all.group_by{|u| u.fullname[0].titleize}.page(params[:page]).per(18)
my view looks like this:
<div class="content">
<%= paginate @members %>
</div>
<% @members.keys.sort.each do |starting_letter| %>
<h3>
<%= link_to starting_letter, {:action => :browse, :controller =>:members, :letter => starting_letter } %>
</h3>
<ol>
<% @members[starting_letter].each do |member| %>
<li>
<% if member.is_artist? %>
<%= link_to member.full_name, member_path(member), :class=>"artist" %>
<% else %>
<%= link_to member.full_name, member_path(member) %>
<% end %>
</li>
<% end %>
</ol>
<% end %>
Here is my error message:
NoMethodError (undefined method `page' for #<Hash:0x007f78d4bf48f8>):
app/controllers/members_controller.rb:10:in `index'
Kaminari adds page
method to ActiveRecord::Relation
but Member.all.group_by
returns hash. That is why you get this exception.
I'd suggest to perform grouping after pagination, e.g.:
@members = Member.order(:full_name).page(params[:page]).per(18).to_a.group_by { |u| u.fullname[0].upcase }
UPDATE
In order to use paginate
helper you could assign 2 variables, e.g.:
@paginated_members = Member.order(:full_name).page(params[:page]).per(18)
@members = @paginated_members.to_a.group_by { |u| u.fullname[0].upcase }
And pass @paginated_members
to the paginate
helper.
这篇关于kaminari 和 order_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!