未定义的方法`each'代表nil:NilClass(显示读取的Crud)

时间:2014-01-04 13:44:11

标签: html ruby-on-rails ruby

我正在尝试使用Ruby on Rails显示数据库的内容,当我编写此代码时,它返回错误"undefined method 'each' for nil:nilclass"。现在我所看到的所有类似问题都表明问题在于控制器。我已经检查了我的控制器,说实话它现在非常简单,它与我在教程中使用的几乎相同(包括Case Sensitive)(对象名称除外)。也许我只是错过了一些非常明显的东西。

查看

 
<div class="item list">
 <h2>Subjects</h2>

<%= link_to("Add New item", {:action => 'new'}, :class => 'action new') %>

 <table class="listing" summary="item list">
    <tr class="header">
        <th>&nbsp;</th>
        <th>Item</th>
        <th>Visible</th>
        <th>Actions</th>
    </tr>
    <% @items.each do |item| %> 
       <tr>
        <td><%= item.position %></td>
        <td><%= item.name %></td>
        <td class="center"><%= item.visible ? 'Yes' : 'No' %></td>
        <td class="actions">
          <%= link_to ("show", {:action => 'show', :id => item.id}, :class => 'action show') %> 
          <%= link_to ("edit", {:action => 'edit', :id => item.id}, :class => 'action edit') %> 
          <%= link_to ("delete", {:action => 'delete', :id => item.id}, :class => 'action delete') %>
        </td>
    </tr>

    <% end %> 
 </table>
</div>

CONTROLLER

class ItemsController < ApplicationController

def list
 @items = Item.order("items.position ASC")
end 
end

其他

Processing by ItemsController#stocklist as HTML
Rendered items/stocklist.html.erb within layouts/application (7.0ms)
Completed 500 internal server error in 17ms

2 个答案:

答案 0 :(得分:0)

我认为变量@itmes确实拥有您愿意获取的数据数组。 尝试调试并在代码下方的@itmes puts @itmes内打印值,看看它是否为空,并使用正确的条件来获取数据,如;

Model.all(:order => 'DATE(updated_at), price')

答案 1 :(得分:0)

好的,所以对于未来的任何人来说Sawa都会让我解决这个问题。

在控制器中它是呼叫列表。 现在......应该一直在调用“stocklist”

class ItemsController < ApplicationController

def stocklist
 @items = Item.order("items.position ASC")
end 
end

这就是错误的。 (生活中的小事情会产生重大影响......)