0

I'm rather new to Ruby on Rails so would appreciate some help

Roles have Users in my application. When showing a role I would like to render a paginated list of user names (and as a further refactor - links to users). Currently my HAML template is as follows

...

  %ul.assigned-users
    - if @role.users.present?
      - names = @role.users.collect {|u|  u.name}
      - links = Kaminari.paginate_array(names).page(params[:page]).per(20)
      = paginate links
    - else
      %p No users have this role assigned

...

Rendering it gives me the pagination links BUT no names.

Oss
  • 4,232
  • 2
  • 20
  • 35
Pavel Murnikov
  • 53
  • 1
  • 10

1 Answers1

0

Kaminari's paginate_array method does not show the values in the array.

The best way to do so is get the query paginated from the database. Kaminari.paginate_array in your code takes in the whole array of users from the database and then paginates it which is highly inefficient and memory consuming.

You need to add the logic to the controller. If you paginate the @role.users query, it is generated with LIMIT which is the value you assign in the per method and OFFSET which equals to (params[:page] - 1) * per. This gets only the number of records you need from the database.

In your controller app/controllers/roles_controller.rb

class ConversationsController < ApplicationController
  def show
   @role = Role.find params[:id]
   @users = @role.users.page(params[:page]).per(20)
  end
end

In your view app/views/roles/show.html.haml

%ul.assigned-users
  - if @users.present?
    - @users.each do |u|
      %li=u.name
    = paginate @users
  - else
    %p No users have this role assigned
Oss
  • 4,232
  • 2
  • 20
  • 35