从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
原因文章控件r是否则@article
将在我们的 视图中为零,并且调用@article.errors.any?
会引发错误。
我的疑问: 如果有错误,而填写表格,如何在new
的@article
了解造成的create
行动@article
实例的错误?他们不是两个不同的变数吗?当我们render 'new'
不应该的create
方法超出范围,其中包含的错误说明和@article
new
不包含错误信息?
如下所述,'render'中的'new'是模板new.html.erb,而不是新的动作。 –