【问题标题】:errors not showing upon editing/updating an article - following rails guide v5.1.4编辑/更新文章时未显示错误 - 遵循 rails guide v5.1.4
【发布时间】: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 文件以供参考。感谢您回答这个问题。
  • &lt;% if @article.errors.any? %&gt; 行下方添加&lt;%= @article.inspect %&gt; 并分享您的收获?
  • 很高兴为您提供帮助!我检查并发现指南中有错误。缺少第 5.11 节local: true

标签: ruby-on-rails ruby-on-rails-5.1


【解决方案1】:

local: true 添加到您的表单中,如下所示:

<%= form_with(model: @article) do |form| %>

收件人:

<%= form_with(model: @article, local: true) do |form| %>

原因在同一指南中说明:

默认情况下,form_with 使用 Ajax 提交表单,从而跳过整页重定向。为了使本指南更易于阅读,我们暂时使用 local: true 禁用了它。

我检查并且指南包含错误。 5.11 节缺失local: true

【讨论】:

  • 正确....指南在前面的部分中确实提到了local:true 的含义。但是在第 5.11 节中,他们错过了local:true 部分。很高兴你没看错。
【解决方案2】:

问题是您忘记添加 local: true。默认情况下,使用 form_with 时的所有请求都是 ajax。所以你需要关闭它

form_with(model: @article, local: true)

在此处link1link2 阅读有关 form_with 的更多信息

【讨论】:

  • 我明白了.. 是的,解决了它。我相信rails指南需要更新。作为一个新手,当我遵循 rails 指南中给出的 sn-ps 时,他们没有在那里提到 local:true。很高兴您正确地选择了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多