【发布时间】:2017-12-07 10:41:20
【问题描述】:
这个问题是Rails 5.1.4入门指南中提到的示例教程所特有的
在遵循 rails 入门指南中的 Section 5.11 [Updating Articles] 后,如果尝试保存具有空标题或空文本的文章,预计将调用 app/views/articles/edit.html.erb 文件中包含 <% if @article.errors.any? %> 的行。意思是,应该显示错误消息。
但是,文章被阻止更新(如预期的那样),但错误消息未显示(如预期的那样)。
有人在 Rails Guide 5.1.4 中解释的入门教程中熟悉这个问题吗?
EDIT::: 以下是控制器文件和视图文件。我添加了一些 puts 语句以打印到控制台
articles_controller,rb 文件:
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(valid_article_params)
puts 'article successfully updated...'
redirect_to @article
else
puts 'article could not be updated...'
render 'edit'
end
end
private
def valid_article_params
params.require(:article).permit(:title, :text)
end
edit.html.erb 文件:
<h1>Edit article</h1>
<%= form_with(model: @article) do |form| %>
<% if @article.errors.any? %>
<% puts 'there are some errors here in edit.html.erb' %>
<div id="error_explanation">
<h3>
<%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:
</h3>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% puts 'errors shown from edit.html.erb' %>
<% 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 %>
【问题讨论】:
-
我们可以看看你的表格吗?
-
请显示您的视图 (edit.html.erb) 以及控制器代码
-
嗨@Snake和@Salil。我添加了
articles_controller.rb文件和edit.html.erb文件以供参考。感谢您回答这个问题。 -
在
<% if @article.errors.any? %>行下方添加<%= @article.inspect %>并分享您的收获? -
很高兴为您提供帮助!我检查并发现指南中有错误。缺少第 5.11 节
local: true
标签: ruby-on-rails ruby-on-rails-5.1