0
我收到以下未定義的方法each
錯誤。 我跟着Lynda上的練習一起跟着我被卡在這裏。我試圖理解其他問題中的解決方案,但仍然超出我的理解範圍。任何幫助將不勝感激。未定義的方法`每個'做主題
ActionView::Template::Error (undefined method `each' for nil:NilClass):
10: <th>Pages</th>
11: <th>Actions</th>
12: </tr>
13: <% @Subjects.each do|subject| %>
14: <tr>
15: <td><%= subject.position %></td>
16: <td><%= subject.name %></td>
app/views/subjects/index.html.erb:13:in `_app_views_subjects_index_html_erb__3548269486732453408_70351994996820'
這裏是在models/views/subjects/index.html.erb
<div class = "subjects index">
<h2>Subjects</h2>
<%= link_to("Add New Subject",'#', :class => 'action new') %>
<table class ="listing" summary ="Subject list">
<tr class = "header">
<th> </th>
<th>Subject</th>
<th>Visible</th>
<th>Pages</th>
<th>Actions</th>
</tr>
<% @Subjects.each do|subject| %>
<tr>
<td><%= subject.position %></td>
<td><%= subject.name %></td>
<td class ="center"><%= subject.visible ? 'Yes' : 'No' %></td>
<td class = "center"><%= subject.pages.size %></td>
<td class = "action">
<%= link_to("Show", '#',:class => 'action show') %>
<%= link_to("Edit", '#' ,:class => 'action edit') %>
<%= link_to("Delete", '#',:class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
</div>
主題模型中定義爲如下的索引代碼:
class Subject < ActiveRecord::Base
has_many :pages
scope :visible, lambda { where(:visible => true) }
scope :invisible, lambda { where(:visible => false) }
scope :sorted, lambda { order("subjects.position ASC") }
scope :newest_first, lambda { order("subjects.created_at DESC")}
scope :search, lambda {|query|
where(["name LIKE ?", "%#{query}%"])
}
end
當i型Subject.all
irb(main):001:0> Subject.all
Subject Load (0.2ms) SELECT `subjects`.* FROM `subjects`
=> #<ActiveRecord::Relation [#<Subject id: 1, name: "Initial Subject", position: 1, visible: true, created_at: "2015-04-28 04:11:54", updated_at: "2015-04-28 04:18:58">, #<Subject id: 2, name: "Revised Subject", position: 2, visible: true, created_at: "2015-04-28 04:15:01", updated_at: "2015-04-28 04:22:12">, #<Subject id: 4, name: "Third Subject", position: 3, visible: false, created_at: "2015-04-28 04:31:04", updated_at: "2015-04-28 04:31:04">]>
您的實例變量'@ Subjects'是大寫字母。這將是'@科目'。 – Emu
也添加控制器代碼。 –
謝謝你解決了這個問題。然而,另一個出現。 這次是'undefined method' name'' 還突出顯示此行 '