在轨道中的字母分页 [英] alphabetical pagination in rails

查看:147
本文介绍了在轨道中的字母分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Rails按字母顺序分页寻找一块宝石。我希望我可以在结果中找到第一个字母的列表(我的意思是,如果没有以'a'开头的行,我不希望'a'显示在分页链接上)。这种宝石是否已经存在?



预先感谢!

解决方案

<例如,如果你有一个 find ,也许就像:

  @all_words = Word.select(words.word)

...它返回了一个结果集,比如这样的单词列表:

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

...您可以这样做:

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

会返回:

  [a,b,d,r,i] 

.collect {| word | word [0,1]} 将每个单词的第一个字母存储到一个新数组中,而 uniq 过滤出唯一的字母和 sort 按字母顺序排序。



简单地将它分配给一个变量,你可以像这样在视图中使用它:

 < ul> 
<%@ first_letters.each do | letter | %GT;
<%= content_tag:li,link_to(letter,words_pagination_url(letter),:title =>按字母分页:#{letter})%>
<%end%>
< / ul>

然后,您的控制器操作可以决定如果传入一个参数,该如何处理分页中的参数:

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

然后模型中的范围看起来像这样:

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



<

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

我还没有测试过这一切,但它应该设置您正确的路径。

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.

这篇关于在轨道中的字母分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆