Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alphabetical pagination in rails

I'm searching a gem for Rails for alphabetical pagination. I wish I could have a list of first letters found in the result (I mean, if there is no row beginning with 'a', I don't want the 'a' to be display on the pagination links). Is this kind of gem already exists?

Thanks in advance!

like image 531
Mathieu Mahé Avatar asked Sep 28 '11 21:09

Mathieu Mahé


3 Answers

This wouldn't be too hard to create at all, for example if you had a find, maybe like:

@all_words = Word.select("words.word")

…which returned a result a result set such as a list of words like this:

["alphabet", "boy", "day", "donkey", "ruby", "rails", "iPad"]    

…the you could do this:

@all_words.collect {|word| word[0,1]}.uniq.sort

which would return:

["a", "b", "d", "r", "i"]

The .collect {|word| word[0,1]} stores the first letter of each word into a new array whilst uniq filters out the unique letters and sort sorts these alphabetically.

Simply assign this to a variable and you can use it in your view like so:

<ul>
<% @first_letters.each do |letter| %>
    <%= content_tag :li, link_to(letter, words_pagination_url(letter), :title => "Pagination by letter: #{letter}") %>
<% end %>
</ul>

Your controller action could then decide what to do with the param from the pagination if one is passed in:

def index
    if params[:letter]
        @words = Word.by_letter(params[:letter])
    else
        @words = Word.all
    end
end

And then the scope in your model would look something like:

scope :by_letter,
        lambda { |letter| {
            :conditions => ["words.word LIKE ?", "#{letter}%"]
        }}

Your routes require something like:

match "words(/:letter)" => "words#index", :as => words_pagination

I haven't tested this all the way through but it should set you on the right path.

like image 87
Pete Avatar answered Sep 20 '22 14:09

Pete


To get a dynamic select from the appropriate table, you can use a dynamic SQL finder.

In this example, we select from a table named 'albums', and fabricate a column 'name' to hold the values. These will be returned in the 'Album' model object. Change any of these names to suit your needs.

Album.find_by_sql("SELECT DISTINCT SUBSTR(name,1,1) AS 'name' FROM albums ORDER BY 1")

Note that you can't use the Album model objects for anything except querying the 'name' field. This is because we've given this object a lobotomy by only populating the 'name' field - there's not even a valid 'id' field associated!

like image 25
agedOne Avatar answered Sep 17 '22 14:09

agedOne


I've created an alphabetical pagination gem here: https://github.com/lingz/alphabetical_paginate

For anyone still having issues in this domain.

like image 35
Xiv Avatar answered Sep 17 '22 14:09

Xiv