tac*_*tac 1 ruby-on-rails ruby-on-rails-5
我的问题是关于官方Rails 指南的第 5.10 节
我有一个带有标题和文本字段的文章模型
文章.rb :
class Article < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
end
Run Code Online (Sandbox Code Playgroud)
文章_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
Run Code Online (Sandbox Code Playgroud)
导游说
@article = Article.new
需要添加到新操作中,否则 @article 在我们看来将为零,并且调用@article.errors.any?将引发错误。这是new.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 %>
Run Code Online (Sandbox Code Playgroud)
我能理解的是,当出现错误时,它会出现在@articles 中,所以@article.errors.any?有助于在呈现“新”视图时显示错误。它确实按预期工作,但我无法理解的是@article = Article.new在新操作中应该重置@article 并且在用户重定向到new. 但不知何故,错误并没有丢失,并且确实正在显示。这是怎么回事?
这两个render和redirect是不同的东西。
render 呈现将作为响应正文返回给浏览器的内容。
redirect或redirect_to- 重定向关注告诉浏览器它需要向不同位置或路径中给定的相同位置发出新请求。
第5.10条明确提到
请注意,在 create 操作中,当 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
Run Code Online (Sandbox Code Playgroud)
编辑:使用 ActiveModel 创建表单对象。表单对象是专门设计用于传递给 form_for 的对象
@article.errors.any?如果@article对象包含任何错误消息,我们总是检查它将执行的错误
请阅读form_for文档。
| 归档时间: |
|
| 查看次数: |
1330 次 |
| 最近记录: |