Alphabetical pagination in rails

I'm looking for a gemstone for Rails for pagination. I would like to have a list of the first letters found as a result (I mean, if there is no line starting with "a", I do not want "a" to appear on page links). Does this kind of gem already exist?

Thanks in advance!

+7
source share
3 answers

It would not be too difficult to create at all, for example, if you had find , it could be like:

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

... which returned the result in a result set, such as a list of words like this:

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

... you could do this:

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

who will return:

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

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

Just assign it to a variable, and you can use it in your view like this:

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

Then your controller action can decide what to do with the parameter from the pagination, if it is passed:

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

And then the area in your model will look something like this:

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

Your routes require something like:

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

I have not tested this completely, but it should set you on the right path.

+11
source

To get a dynamic selection from the corresponding table, you can use dynamic SQL search.

In this example, we select from a table named "albums" and create a column name to store the values. They 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") 

Please note: you cannot use album model objects for anything other than querying the name field. This is due to the fact that we provided this object with a lobotomy only by filling out the "name" field - there was not even a valid "id" field there!

+5
source

I created an alphabetical pearl: https://github.com/lingz/alphabetical_paginate

For those who still have problems in this domain.

+5
source

All Articles