Rails undefined method `each' for nil:NilClass

guojinlong · 2014年09月20日 · 最后由 zmy 回复于 2016年08月31日 · 10468 次阅读

学习 rails 入门的时候,写到:

<h1>Listing articles</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
  </tr>

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
    </tr>
  <% end %>
</table>```
报如标题的错。
在controller中我是写的没有错:@articles = Article.all

为什么会爆:
undefined method `each' for nil:NilClass

#1 楼 @michael0015 你是说我的@articles查出来时空的吗?

先判断是否为空

scope 返回的都是集合,看看是不是控制器代码写错了

把完整的错误信息贴过来。

class ArticlesController < ApplicationController def new @article = Article.new end

def create @article = Article.new(article_params)

if @article.save redirect_to @article else render 'new' end end

def show @article = Article.find(params[:id]) end

def edit @article = Article.find(params[:id]) end

def update @article = Article.find(params[:id])

if @article.update(article_params) redirect_to @article else render 'edit' end end private def article_params params.require(:article).permit(:title, :text) end

def index @articles = Article.all end end 问题解决了,因为我把 index 写在了 private 下面了。所以@articles估计是在页面就取不到了。但是 index 这个函数却还能访问,奇怪。。。 谢谢大家!!!

#6 楼 @guojinlong 因为 rails 如果找不到 action 回去找同名的 view

#7 楼 @saiga 你是说首先找不到 index,后来就去找同名 index,就算在 private 中用这个 index 的意思吗?

你把 index 写在了 private 下面,肯定是访问不到 index 方法了,但是这种情况下 rails 会继续渲染 index.html.erb, 这时 @articles 为 nil, 就造成了错误,如果能访问到 index 方法,@articles 就不会是 nil。你可以试试把 index 方法去掉,会报同样的错误。

#9 楼 @kayakjiang 哦。明白你说的意思了。谢谢大神!

#10 楼 @guojinlong 从各种坑中爬过的码农而已,举手之劳不用客气。

@guojinlong 你好,我也在学习 rails 教程的时候碰到了这个问题,但是为什么我将 index 方法放在了 private 的上面,依然还是同样的错误呢?

#12 楼 @com3345 难道还有个 protect?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号