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]
...
private
 ...
  def set_initials
    @first_letters = Object.select("DISTINCT LOWER(SUBSTR(tablename.name, 1, 1)) AS name").order("name").collect{|fl| "#{fl.name}"}
  end

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

app/views/object/_by_letter.html.erb

<% @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' %>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s