为什么group_by方法会更改对象的属性?

时间:2017-07-22 14:22:13

标签: ruby-on-rails group-by

我正在尝试显示按创建时间分组的注释对象。我可以在没有组的情况下正确显示它们,但是当我尝试分组时,我似乎失去了对对象属性的引用。这是我得到的错误:

undefined method `title' for #<Array:0x0000000aeb52d0>

在这一行:

<%= link_to note.title, {:action => 'show', :id => note.id} -%>

以下是该观点的相关部分:

<ul id = "notes">
    <% @notes.group_by(&:created_at).each do |note| %>
    <li>
        <%= link_to note.title, {:action => 'show', :id => note.id} -%>
        <% if note.category == 0%>
            <%= label_tag 'category', 'Note' %>
        <% else %>
            <%= label_tag 'category', 'Goal' %>
            <%= note.dueDate %>
        <% end %>
    </li>
    <% end %>
</ul>

以下是迁移:

class Notes < ActiveRecord::Migration[5.1]
  def change
    create_table :notes do |t|
        t.string :title, limit: 40, null: false
        t.boolean :category, default: false, null: false
        t.string :description, limit: 1000
        t.string :dueDate
        t.timestamps
    end
  end
end

1 个答案:

答案 0 :(得分:1)

Enumerable#group_by方法返回hash,其中key是您要分组的属性(created_at),value是具有相同属性值的对象数组。

Notes.all.group_by(&:created_at)
=> {Sat, 22 Jul 2017 15:54:24 UTC +00:00=>[#<Notes id:1 ... >]}

因此,如果您出于某种原因对笔记进行分组,则可能需要显示分组的注释。例如:

<div id = "notes">
  <% @notes.group_by(&:created_at).each do |created_at, notes| %>
    <div> <%= created_at %> </div>
    <ul class="grouped-notes">
      <% notes.each do |note| %>
        <li>
            <%= link_to note.title, {:action => 'show', :id => note.id} -%>
            <% if note.category == 0%>
                <%= label_tag 'category', 'Note' %>
            <% else %>
                <%= label_tag 'category', 'Goal' %>
                <%= note.dueDate %>
            <% end %>
        </li>
      <% end %>
    </ul>
  <% end %>
</div>