0

我是一个新手,在使用 Rails 2nd 进行敏捷 Web 开发时遇到问题。Ruby 版本 1.8.6。当本书指示我将脚手架产品放入 admin_controller.rb 时,问题就开始了。我删除了该行,现在我收到以下错误消息。

Admin#index 中的 NoMethodError 显示第 10 行引发的 admin/index.html.erb:

当你没想到时,你有一个 nil 对象!您可能期望有一个 Array 的实例。评估 nil.each 时发生错误

提取的源代码(第 10 行附近):

7:     <th>Image url</th>
8:   </tr>
9: 
10: <% for product in @product %>
11:   <tr>
12:     <td><%=h product.title %></td>
13:     <td><%=h product.description %></td>

RAILS_ROOT: C:/InstantRails-2.0-win/rails_apps/depot

这是控制器信息:admin_controller class AdminController < ApplicationController end

这是视图信息:Views\admin\index.html.erb

列出产品

<table>
  <tr>
    <th>Title</th>
    <th>Description</th>
    <th>Image url</th>
  </tr>

<% for product in @product %>
  <tr>
     <td><%=h product.title %></td>
    <td><%=h product.description %></td>
    <td><%=h product.image_url %></td>
    <td><%= link_to 'Show', product %></td>
    <td><%= link_to 'Edit', edit_product_path(product) %></td>
    <td><%= link_to 'Destroy', product, :confirm => 'Are you sure?', :method          => :delete %></td>
      </tr>
<% end %>
</table>

<br />

<%= link_to 'New product', new_product_path %>

这是模型信息: Models\product.rb class Product < ActiveRecord::Base end

有什么建议吗?

4

1 回答 1

3

听起来@products 没有在您的控制器中设置,并且您的视图中也可能存在拼写错误:

在 views\admin\index.html.erb 中,更改:

 <% for product in @product %>  

至:

 <% for product in @products %>

并确保您的控制器具有:

admin_controller.rb

class AdminController < ApplicationController 

  def index
    @products = Product.all
  end

end
于 2012-02-09T18:47:30.813 回答