红宝石按字母顺序排列的列表 [英] Alphabetical lists with ruby on rails

查看:94
本文介绍了红宝石按字母顺序排列的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个列表,该列表将按字母排序,并正在寻找一种解决方案来获取数据库结果并按字母顺序对其进行排序.

I am building a list that will be sorted by the alphabet and am looking for a solution to grab the database result and sort it alphabetically.

任何帮助将不胜感激!

推荐答案

嗯,如果列表不太庞大,您可能会天真地像这样:

Hmm, if you have a list that isn't too massive you might just do it naively like:

(假设您有一个具有name属性的模型Company)

(This assumes you have a model Company which has a name attribute)

@grouped = {}
Company.all.each do |company|
  letter = company.name.slice(0,1).upcase
  @grouped[letter] ||= []
  @grouped[letter] << company
end

现在,您可以执行以下操作:

And now you can, in your view, do something such as:

<ul>
  <% @grouped.keys.sort.each do |letter| -%>
    <li>
      <h2><%= letter %></h2>
      <ul>
        <% @grouped[letter].each do |company| -%>
          <li><%= company.name %></li>
        <% end -%>
      </ul>
    </li>
  <% end -%>
</ul>

更新:如果要扩展字母"的含义,则可能将逻辑移至模型中,例如:

Update: If you want to extend the logic on what the 'letter' is, you would probably move the logic into the model, eg:

class Company
  # ... code

  def initial
    # find a number at the start of the string if it exists
    m = self.name.match(/^\d+/)
    return m[0] if m
    # or return the first letter upcased otherwise
    return self.name.slice( 0, 1 ).upcase
  end
end

这篇关于红宝石按字母顺序排列的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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