2017-07-22 69 views
0

我想顯示註釋對象的創建時間。我可以在沒有分組的情況下正確顯示它們,但是當我嘗試分組時,它似乎正在失去對對象屬性的引用。這是我得到的錯誤:爲什麼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 
+0

只是對代碼的小意見。 Ruby on Rails有幾個與命名模型類和列有關的約定。模型類應以單數形式命名(例如Note),但表名應以複數形式(註釋)。列名應該寫入snake_case,例如due_date。 –

回答

1

Enumerable#group_by方法retu rns 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> 
相關問題