在视图上显示验证错误"new"



在Rails指南的这一部分中,指示在new方法中添加@article = Article.newArticlesController,并解释说否则我们将无法访问@article.errors

据我了解,@articles = Article.new创建了一个新的Article实例,我们需要的是尝试提交的@article变量。我知道它有效,但我需要了解为什么。

控制器代码:

class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
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_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 articles 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 %>
<% end %>
<%= link_to 'Back', articles_path %>

它说:

我们添加的原因 @article = Article.new 在 文章控制器是否则@article在我们的 查看,并调用@article.errors.any?会抛出错误。

因此,它与访问验证错误无关。

如果操作中没有@article变量new您将在nil值的视图中调用errors方法,而nil没有这样的方法,因此您会undefined method 'errors' for nil:NilClass收到错误。如果@article变量设置为Article.new则在Article类实例上调用errors方法,并且由于尚无验证错误,因此不会呈现#error_explanation块。

但是,当您尝试创建新记录时,将进行验证。如果存在验证错误,您的 rails 应用程序会再次呈现new模板,但它会通过create操作执行此操作。因此,这次的@article变量是来自create方法的变量,由于我们在其中存在验证错误,因此将呈现#error_explanation块,用户将看到出了什么问题。

最新更新