Sirrah025
Sirrah025

Reputation: 85

Why am I getting an undefined method `errors' for nil:NilClass?

I am doing the 5.11 part of the getting started with Ruby on Rails guide. When I try to edit an article on the local server, I get the error.

I am trying to learn Ruby on Rails for a class project. Part of the project is having a working demonstration of the framework that I have to present to the class.

This is the code for the articles_controller:

class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
  end

  def index
    @articles = Article.all
  end

  def edit
    @articles = Article.find(params[:id])
  end

  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 update
    @article = Article.find(params[:id])

    if @article.update article_params
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private

  def article_params
    params.require(:article).permit :title, :text
  end
end

And this is the code for editing an article:

<h1>Edit article</h1>

 <%= form_with model: @article, local: true do |form| %>

   <% if @article.errors.any? %>
     <div id="error_explanation">
       <h2>
         <%= pluralize(@article.errors.count, "error") %> prohibited
         this article from being saved:
       </h2>
       <ul>
         <% @article.errors.full_messages.each do |msg| %>
           <li><%= msg %></li>
         <% end %>
       </ul>
     </div>
   <% end %>

   <p>
     <%= form.label :title %><br>
     <%= form.text_field :title %>
   </p>

   <p>
     <%= form.label :text %><br>
     <%= form.text_area :text %>
   </p>

   <p>
     <%= form.submit %>
   </p>

 <% end %>

<%= link_to 'Back', articles_path %>

I expected to be able to edit an article and save it. Instead, I get an error saying that the method 'errors' is undefined.

Upvotes: 1

Views: 40

Answers (1)

Sujan Adiga
Sujan Adiga

Reputation: 1371

There seems to be a typo in your edit action. You should be assigning the result of Article.find(params[:id]) to @article and not @articles

Note that instance variables in Ruby will have a default value of nil

Upvotes: 1

Related Questions