NoMethodError in Welcome # index Ruby On Rails

0

I'm doing a blog in Ruby on Rails and I have this error:

  

NoMethodError in Welcome # index

     

undefined method 'each' for nil: NilClass

<% @articles.each do |article| %>
  <h1><%= article.title %></h1>
  <div>
    <%= article.body %>
  </div>
<% end %>

I already tried everything and according to me I'm not making any mistakes.

This is my controller:

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end
end

This is my routes.rb:

Rails.application.routes.draw do
  resources :articles
  root 'welcome#index'
end
    
asked by isalvinator 10.07.2017 в 07:27
source

1 answer

3

The problem is that you want to use the variable @articles in the view app/views/welcome/index.html.erb , however this is not defined in the action index of the controller Welcome .

To fix the problem you have two options:

  • Change the root of your application to articles#index :

    Rails.application.routes.draw do
      resources :articles
      root 'articles#index'
    end
    

    If you take this option, verify that you have the app/views/articles/index.html.erb view.

  • Add variable @articles in welcome#index :

    def WelcomeController < ApplicationController
      def index
        @articles = Article.all
      end
    end
    
  • answered by 11.07.2017 в 02:50