ruby app/views/articles/new.html.erb中nil:NilClass的未定义方法“errors”

n1bvdmb6  于 12个月前  发布在  Ruby
关注(0)|答案(4)|浏览(89)

我跟随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

我的新.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是否在创建之前进行了验证?我该如何解决?

pxq42qpu

pxq42qpu1#

你的模型和控制器都被合并到一个类中。这行不通
你需要两个类:

  • 一个名为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中的new和create操作更改为:

def new
  @article = Article.new
end

def create
  @article = Article.new(article_params)

  # ...
0x6upsns

0x6upsns2#

validate部分应该位于Modal中,即Article < ActiveRecord::Base。你的代码的其余部分应该是文章控制器

xkrw2x1b

xkrw2x1b3#

你必须把你的验证放在你的模型中:

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| %>
3bygqnnd

3bygqnnd4#

在新的.html.erb文件下,替换以下行:

<% if @article.errors.any? %>

用这个:

<% if form.object.errors.any? %>

相关问题