nil:NilClass 的未定义方法 `each'...为什么?

问题描述 投票:0回答:4

rails 指南示例,单击按钮保存帖子,控制台显示此消息:

于 2013-12-25 22:42:04 +0800 开始为 127001 发布“/posts” 由 PostsController#create 作为 HTML 参数处理: {“utf8”=>“✓”,“authenticity_token”=>“CLalUww3gqnSlED0AWdou6P/U2qya vPqDiBANQOuYgA=", "post"=>{"title"=>"11", "text"=>"22"}, "commit"=>"Save Post"} (0.0ms) 开始事务 (0.0ms) 回滚事务重定向到http://127001:3000/posts 16 毫秒内完成 302 个发现(ActiveRecord:0.0 毫秒)

于2013-12-25 22:42:04 +0800开始获取127001的“/posts” 由 PostsController#index 处理为 HTML 渲染 布局/应用程序内的 posts/index.html.erb (15.6ms) 已完成 500 31ms 内服务器内部错误

ActionView::Template::Error(未定义方法“each” 无:无类):

        <th>Text</th>
        </tr>
        <% @posts.each do |post| %>

====================================================== =====

路线是正确的,为什么帖子为零? Rails 4.0.2 红宝石 2.0

ruby-on-rails undefined
4个回答
35
投票

在您的帖子控制器中,您需要定义

@posts
,这是基于您没有的错误。

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end 

由于

@posts
未定义,因此调用
each
将会为 nil:NilClass` 生成
undefined method
each'。


13
投票

每当您遇到此错误时,请解释更多有关此错误的信息

  undefined method `each' for nil:NilClass

该错误清楚地抱怨您在此处(@posts)上调用每个方法,而该方法为零。这意味着您尚未在控制器中定义它。由于您没有定义它,这就是为什么它抱怨 nil 类的未定义方法。

请务必在从视图中调用实例变量时进行检查?您必须在控制器中定义它才能在视图中访问。

有时,如果您在控制器中调用私有方法,也会收到此错误。


3
投票

尝试更换这个:

<% @posts.each do |post| %>

<% Post.all.each do |post| %>

0
投票

就我而言,这有效...... <% Article.all.each do |post| %>

但是我确实想使用变量“@article”,在控制器中定义为:

PstArticlesController 类 < ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end end Thanks!

© www.soinside.com 2019 - 2024. All rights reserved.