gpt4 book ai didi

ruby-on-rails - 未定义方法 `errors' 为 nil :NilClass in app/views/articles/new. html.erb

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:04 30 4
gpt4 key购买 nike

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

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在创建之前是否正在验证?我该如何解决?

最佳答案

您的模型和 Controller 都啮合在一起成为一个类。那行不通。

你需要两个类:

  • 一个名为 Article 的模型继承自 ActiveRecord::Base
  • 一个名为 ArticlesController 的 Controller 继承自 ApplicationController

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

您所遵循的指南说(注意文件名):

Rails includes methods to help you validate the data that you send to models. Open the app/models/article.rb file and edit it:

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

下面是

... to do this, change the new and create actions inside app/controllers/articles_controller.rb to these:

def new
@article = Article.new
end

def create
@article = Article.new(article_params)

# ...

关于ruby-on-rails - 未定义方法 `errors' 为 nil :NilClass in app/views/articles/new. html.erb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30217204/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com