开发者

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!


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.


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!


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

For anyone still having issues in this domain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜