我的问题是关于官方Rails指南的第5.10节
我有一个文章模型,包含字段标题和文本
文章.rb:
class Article < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
end
articles_controller.rb:
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
导游说
@article=article.new
需要添加到新操作中,否则在我们看来@article将为零,并且调用@article.errors.any?
将引发错误。这是新的.html.erb:
<%= 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 article 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 %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
我能理解的是,当出现错误时,它出现在@article.so@article.errors.any中?有助于在呈现"新"视图时显示错误。它确实如预期的那样工作,但我无法理解的是,新操作中的@article = Article.new
应该重置@文章,并且在用户重定向到new
后,错误应该会丢失。但不知何故,这些错误并没有丢失,而且确实在显示出来。这是怎么发生的?
render
和redirect
都是不同的东西。
-
render
将返回到浏览器的内容呈现为响应体。 -
redirect
或redirect_to
-重定向是指告诉浏览器它需要向路径中给定的不同位置或相同位置发出新请求。
第5.10节中明确提到
请注意,在创建操作中,当save返回false时,我们使用render而不是redirect_to。使用render方法是为了在渲染@article对象时将其传递回新模板。这种呈现是在与表单提交相同的请求中完成的,而redirect_to会告诉浏览器发出另一个请求。
注意:您可以详细阅读的渲染与重定向
根据您的问题
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new' # this will add error (validations)
end
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
redirect_to 'new' # this will not add any error as this is new request and @article will initialise again.
new #same as redirect
end
end
编辑:使用ActiveModel创建表单对象。表单对象是专门为传递给form_for 而设计的对象
我们总是检查错误@article.errors.any?
,如果@article
对象包含任何错误消息,它将执行
请阅读form_for文档。
render
不在new
方法中运行任何代码,它只使用new.html.x
视图。因此,@article = Article.new
从不被执行。
如果您想运行new
中的代码,您需要实际调用该方法:
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
new #actually runs the code in the 'new' method
render 'new' # doesn't go anywhere near the new method, just uses its view
end
end