Rails 按模型中的索引顺序分组 object
Rails grouping object by indexing order in model
我从数据库中获取单词列表并使用
排序
@notes_list_title_asc = current_user.notes.order(:title)
这就是我列出单词的方式
<% @notes_list.each do |note| %>
<li>
<span class="title"><%= link_to note.title, edit_note_path(note) %></span>
<span class="updated"><%= time_ago_in_words(note.updated_at).gsub('about','') + ' ago' %></span>
</li>
<% end %>
我想订购我的单词列表,例如字典,其中 A 作为单词的标题,例如 Article,B 作为 Brother。
是的,有办法。但我不知道如何。提前致谢
您可以 group_by 每个单词的第一个字母。
current_user.notes.order(:title).group_by { |note| note.title[0] }
所以在你的控制器中:
@notes = current_user.notes.order(:title).group_by { |note| note.title[0] }
在您看来:
- @notes.each do |letter, notes|
%h3= letter
%ul
- notes.each do |note|
%li
%span.title= link_to note.title, edit_note_path(note)
%span.updated= time_ago_in_words(note.updated_at).gsub('about', '') + ' ago'
编辑:
order(:title)
按字母顺序排列您的笔记。 group_by
将可枚举对象收集到集合中,按块的结果分组 (source)。
因此,块 returns 笔记标题的第一个字母。因此,您的笔记按笔记标题的第一个字母分组。
您收到一个哈希值:{ "A" => [Note1, Note2], "B" => [Note3] }
.
在您看来,您遍历哈希。对于每个字母,您都有一系列注释。然后您遍历该笔记数组以显示每个笔记。
为了得到字符串的第一个字母:"example"[0]
给你"e"
.
我从数据库中获取单词列表并使用
排序@notes_list_title_asc = current_user.notes.order(:title)
这就是我列出单词的方式
<% @notes_list.each do |note| %>
<li>
<span class="title"><%= link_to note.title, edit_note_path(note) %></span>
<span class="updated"><%= time_ago_in_words(note.updated_at).gsub('about','') + ' ago' %></span>
</li>
<% end %>
我想订购我的单词列表,例如字典,其中 A 作为单词的标题,例如 Article,B 作为 Brother。
是的,有办法。但我不知道如何。提前致谢
您可以 group_by 每个单词的第一个字母。
current_user.notes.order(:title).group_by { |note| note.title[0] }
所以在你的控制器中:
@notes = current_user.notes.order(:title).group_by { |note| note.title[0] }
在您看来:
- @notes.each do |letter, notes|
%h3= letter
%ul
- notes.each do |note|
%li
%span.title= link_to note.title, edit_note_path(note)
%span.updated= time_ago_in_words(note.updated_at).gsub('about', '') + ' ago'
编辑:
order(:title)
按字母顺序排列您的笔记。 group_by
将可枚举对象收集到集合中,按块的结果分组 (source)。
因此,块 returns 笔记标题的第一个字母。因此,您的笔记按笔记标题的第一个字母分组。
您收到一个哈希值:{ "A" => [Note1, Note2], "B" => [Note3] }
.
在您看来,您遍历哈希。对于每个字母,您都有一系列注释。然后您遍历该笔记数组以显示每个笔记。
为了得到字符串的第一个字母:"example"[0]
给你"e"
.