![](/img/trans.png)
[英]How to fix ArgumentError - First argument in form cannot contain nil or be empty: app/views/cars/new.html.erb:8
[英]undefined method `errors' for nil:NilClass in app/views/articles/new.html.erb
我正在关注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
错误undefined method errors' for nil:NilClass
因为这行中的错误<% if @article.errors.any? %>
<% if @article.errors.any? %>
我在这里想念什么。 看起来@article
在创建之前已通过验证? 我该如何解决?
您的模型和控制器都被划分为一个类别。 那行不通。
您需要两个类:
ActiveRecord::Base
继承的名为Article
的模型 ApplicationController
名为ArticlesController
的控制器 您发布的代码是模型,但是您添加的操作( new
和create
)需要进入控制器 。
您所遵循的指南说(请注意文件名):
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) # ...
验证部分应该位于Modal中,该形式为Article <ActiveRecord :: Base。 其余的代码应该是Article控制器
您必须将验证放入模型中:
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| %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.