所以我正在关注 http://guides.rubyonrails.org/getting_started.html 上的官方 ROR 教程 我被困在第 5.8 节,它教我如何列出所有文章
下面是我的controller和index.html.erb
Controller
class ArticlesController < ApplicationController
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def show
@article = Article.find(params[:id])
end
def index
@article = Article.all
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
index.html.erb
<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>
我收到带有错误消息的 NoMethodError in Articles#index
undefined method `each' for nil:NilClass"
怎么了?我从网站上复制并粘贴了代码以查看我做错了什么,但仍然无法修复它。
最佳答案
使用@articles
而不是@article
def index
@articles = Article.all ## @articles and NOT @article
end
@articles
(复数)在语义上是正确的,因为您将在 View 中显示文章集合而不是单篇文章。
你遇到了错误
undefined method `each' for nil:NilClass
因为在 index
操作中,您已经实例化了实例变量 @article
(NOTICE singular) 并且正在使用 @articles
(NOTICE plural) 在您的 index
View 中,即 index.html.erb
。因此,在 View 中,@articles
(复数)将是 nil
,因为它从未设置过。因此,错误。
关于ruby-on-rails - 文章#index 中的 Ruby on Rails 教程 NoMethodError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23639075/