nil的undefined方法`errors':app / views / articles / new.html.erb中的NilClass

时间:2015-05-13 14:02:17

标签: ruby-on-rails ruby

我正在关注http://guides.rubyonrails.org/getting_started.html并尝试向文本字段添加验证。我的班级:

class Article < ActiveRecord::Base

    validates :title, presence: true, length: { minimum: 5 }

    def new
      @article = Article.new
    end

    def create
    @article = Article.new(article_params)

      if @article.save
        redirect_to @article
      else
        render 'new'
        end
    end

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

end

我的new.html.erb文件:

<%= form_for :article, url: articles_path do |f| %>

  <% 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>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

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

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

<% end %>

当我尝试添加新文章时,我会打开http://localhost:3000/articles/new,但由于此行中的错误undefined method errors' for nil:NilClass

而不是表单,因此我看到错误<% if @article.errors.any? %>

我在这里缺少什么。看起来@article在创建之前正在验证?我该如何解决?

3 个答案:

答案 0 :(得分:7)

您的模型和控制器都被拼接成一个类。那不行。

您需要两个类:

  • 一个名为Article的模型,它继承自ActiveRecord::Base
  • 一个名为ArticlesController的控制器,它继承自ApplicationController

您发布的代码是模型,但您添加的操作(newcreate)需要进入控制器

您关注的指南说明(请注意文件名):

  

Rails包含一些方法,可帮助您验证发送给模型的数据。打开 app / models / article.rb 文件并进行编辑:

class Article < ActiveRecord::Base
    validates :title, presence: true,
             length: { minimum: 5 }
end

以下,

  

...为此,将 app / controllers / articles_controller.rb 中的新操作和创建操作更改为:

def new
  @article = Article.new
end

def create
  @article = Article.new(article_params)

  # ...

答案 1 :(得分:0)

验证部分应该位于Modal,即Article&lt;的ActiveRecord :: Base的。你的代码的其余部分应该是文章控制器

答案 2 :(得分:0)

您必须在模型中进行验证:

class Article < ActiveRecord::Base
  validates :title, presence: true, length: { minimum: 5 }
end

你的行动应该在控制器中:

class ArticlesController < ApplicationController

  def new
    @article = Article.new
  end

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

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


end

最后改变你的形式:

<%= form_for @article do |f| %>