取自http://guides.rubyonrails.org/getting_started.html
的示例代码控制器
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
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 %>
<%= link_to 'Back', articles_path %>
此链接中的声明
我们之所以添加
@article = Article.new
ArticlesController是我们的@article
将是零 查看,调用@article.errors.any?
会引发错误。
我怀疑:
如果填写表单时出错,@article
中的new
如何了解@article
create
动作的render 'new'
实例所导致的错误?他们俩都有不同的变数吗?当我们@artcle
不应该create
@article
new
方法超出保留错误说明的范围时,watch
while sleep 1; do tput clear; cat file.txt; done
不包含任何错误信息?
答案 0 :(得分:1)
当from pygame import sprite, foo, bar, ...
创建中出现任何错误时,没有重定向但是渲染意味着它只会@article
新的操作视图,即render/display
,而无需进行新操作或更确切地说,没有再次呼吁采取新行动。请参阅此http://brettu.com/rails-daily-ruby-tip-28-whats-the-difference-between-redirect_to-and-render-in-rails/
当它将呈现new.html.erb时出现错误,它将使用new.html.erb
对象,该对象具有从这些行中获得的所有错误
@article
因此,基本上在您提交表单后,新操作的目的就完成了。现在整个事情将由创建操作处理,其中在错误时它将显示错误并使用您在创建操作中初始化和保存的 @article = Article.new(article_params)
@article.save #save basically runs the validations
对象,并且在成功创建时它将再次调用以使用重定向显示操作
希望它有意义。