So I'm following the official ROR tutorial at http://guides.rubyonrails.org/getting_started.html and I am stuck at section 5.8 where it teaches me how to list out all the articles
The following are my controller and 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>
I am getting the NoMethodError in Articles#index
with the error message
undefined method `each' for nil:NilClass"
What's wrong? I literally copied and pasted the code from the website to see what I'm doing wrong, but still cannot fix it.
Use @articles
and not @article
def index
@articles = Article.all ## @articles and NOT @article
end
@articles
(plural) is semantically correct as you would be displaying a collection of articles in your view and not a single article.
You are getting error
undefined method `each' for nil:NilClass
because in the index
action, you have instantiated the instance variable @article
(NOTICE singular) and are using @articles
(NOTICE plural) in your index
view i.e., index.html.erb
. So, in the view @articles
(plural) would be nil
as it was never set. Hence, the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With