kaminari and order_by

2020-07-23 07:03发布

问题:

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'

回答1:

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.