学习 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
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 这个函数却还能访问,奇怪。。。 谢谢大家!!!
你把 index 写在了 private 下面,肯定是访问不到 index 方法了,但是这种情况下 rails 会继续渲染 index.html.erb,
这时 @articles 为 nil, 就造成了错误,如果能访问到 index 方法,@articles 就不会是 nil。你可以试试把 index 方法去掉,会报同样的错误。
@guojinlong 你好,我也在学习 rails 教程的时候碰到了这个问题,但是为什么我将 index 方法放在了 private 的上面,依然还是同样的错误呢?