Ruby on Rails alphabetic pagination

1. Create a model scope to limit the searching

# Filter host names by their first letter - used for alphabetic pagination
scope :by_letter, ->(initial) {where("name LIKE \'#{initial}%\'").order(:name) }

2. Make the search criteria available to the controller and keep it sticky in the session

    session.delete :object_letter if params[:q]
    session[:object_letter] ||= params[:q]

3. Limit the records selected by the index

@objects = Object.by_letter(session[:object_letter]).paginate :page => params[:page], :per_page => 25

4. Prepare a list of intials and ensure that they are set in the controller only when indexing and searching

before_action :set_initials, only: [:index, :search]
  def set_initials
    @first_letters ="DISTINCT LOWER(SUBSTR(, 1, 1)) AS name").order("name").collect{|fl| "#{}"}

5. Construct a partial template to create the form for display


<% @first_letters.each do |lt|%>
  <%= lt != (session[:object_letter]) ? link_to(lt, objects_url+"?q="+lt )+" " : "<span class='digg_pagination disabled'>#{lt}</span>".html_safe %>
<% end %>
<%= link_to('All', objects_url+"?q=" ) %>

This is not a shared partial template because it includes specific URL references.

6. Render the partial on the index page underneath the main numerical pagination.

<%= render :partial => 'by_letter' %>

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.