Lê Văn Ngọc
Lê Văn Ngọc

Reputation: 1

Why is the object nil in this view?

I want to create a new article object, but have this error:

Showing /Users/levanngoc/code/blog_app/app/views/articles/new.html.erb where line #3 raised:

undefined method `errors' for nil:NilClass

error screenshot

How can I fix it?

this is my controller:

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

  def edit
  end
  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
  end
  def destroy
  end

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

this is my view file: new.html.erb

<h1>New Article</h1>
<%= form_with scope: :article,url: articles_path , 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 %>

Upvotes: 0

Views: 82

Answers (2)

Pierre Thierry
Pierre Thierry

Reputation: 5129

Your new view uses @article but the new action in the controller doesn't create this instance variable. You must change it to:

def new
  @article = Article.new
end

Upvotes: 2

B&#249;i Nhật Duy
B&#249;i Nhật Duy

Reputation: 322

You must declare: @article = Article.new

Upvotes: 1

Related Questions