未定义的方法`每个'做主题

时间:2015-04-30 04:27:34

标签: ruby-on-rails ruby-on-rails-4 undefined

我收到以下未定义的方法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>&nbsp;</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

当我输入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">]>

1 个答案:

答案 0 :(得分:1)

您的@Subjects是大写的,所以这是空的。另请先检查@subjects.present?,然后再循环检查每个。