Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails tutorial NoMethodError in Articles#index

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.

like image 658
user3277633 Avatar asked May 13 '14 18:05

user3277633


1 Answers

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.

like image 146
Kirti Thorat Avatar answered Sep 20 '22 20:09

Kirti Thorat