ruby-on-rails - 无效的创建方法不会引发任何错误

标签 ruby-on-rails validation error-handling

我有一个表单可以为通讯录创建新的联系人。在模型中,first_name和last_name字段是必需的:
型号/contact.rb

class Contact < ApplicationRecord
  [...]
  validates :first_name, :last_name, presence: true
end
如果创建新联系人时出现错误,我有代码应显示消息:
views/contacts/_form.html.erb
<%= form_with model: @contact do |form| %>

  <% if @contact.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@contact.errors.count, "error") %> prevented this contact from being saved:
      </h2>
      <ul>
        <% @contact.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= form.label :salutation %><br>
    <%= form.select :salutation, options_for_select([['Mr.'], ['Mrs.'], ['Ms.'], ['Mx']]), class: "form-control"  %><br>
    <%= form.label :first_name, "First Name*" %><br>
    <%= form.text_field :first_name, class: "form-control" %><br>
    <%= form.label :middle_name, "Middle Name" %><br>
    <%= form.text_field :middle_name, class: "form-control" %><br>
    <%= form.label :last_name, "Last Name*" %><br>
    <%= form.text_field :last_name, class: "form-control" %>
    [...]
输入缺少名字或姓氏的联系人时,不会创建该联系人,并且页面仍停留在表单上。但是, View 顶部不会出现任何错误。我在 Controller 中添加了一些调试功能,发现尽管提交无效,但未创建任何错误:
Controller /contacts_controller.rb
[...]
 def create
    @contact = Contact.new(contact_params)
    logger.debug "New contact: #{@contact.attributes.inspect}"
    logger.debug "Contact should have errors: #{@contact.errors.any?}"
    logger.debug "Contact should be invalid: #{@contact.invalid?}"
[...]
这将在终端中产生以下响应:
Started POST "/contacts" for ::1 at 2020-09-28 11:42:47 +0200
Processing by ContactsController#create as JS
  Parameters: {"authenticity_token"=>"2GBdtJXn77B9+IQuXg03C9HFgMS+ayzqP5lke49HcsvcM02L6lgyoGXuOtKL72mBzNsFU6EawC2dU+mN6RZzkA==", "contact"=>{"salutation"=>"Mrs.", "first_name"=>"Sue", "middle_name"=>"", "last_name"=>"", "ssn"=>"", "dob"=>"", "comment"=>""}, "commit"=>"Create Contact"}
New contact: {"id"=>nil, "salutation"=>"Mrs.", "first_name"=>"Sue", "middle_name"=>"", "last_name"=>"", "ssn"=>"", "dob"=>"", "comment"=>"", "created_at"=>nil, "updated_at"=>nil}
Contact should have errors: false
Contact should be invalid: true
  Rendering contacts/new.html.erb within layouts/application
  Rendered contacts/_form.html.erb (Duration: 4.7ms | Allocations: 1484)
  Rendered contacts/new.html.erb within layouts/application (Duration: 5.0ms | Allocations: 1569)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 70ms (Views: 20.1ms | ActiveRecord: 27.1ms | Allocations: 18926)
这对我来说很奇怪:联系人应该有错误:false;联系人应该无效:true
据我所知,我在模型中的验证是正确的,并且提交被识别为无效,但是由于某种原因,这不会转换为错误。我需要更改什么?
任何帮助都将非常棒!谢谢您的光临。
编辑:
这是完整的create方法,其中包括.save方法:
def create
    @contact = Contact.new(contact_params)

    if @contact.save
      redirect_to @contact, notice: 'Contact was successfully created'
    else
      render 'new'
    end
  end
这是尝试提交无效请求后的网页图像:
network tab view with errors displayed

最佳答案

Contact.new初始化一个新的Contact对象,但不对其进行验证或存储。
调用valid?invalid?进行验证。这会将错误添加到记录中。如果在其上调用save(或save!),它还将在存储记录之前运行验证。

关于ruby-on-rails - 无效的创建方法不会引发任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64099742/

相关文章:

ruby-on-rails - 使用 jsonb 数组的 Rails (postgres) 查询

ruby-on-rails - Postgresql.app 与 Homebrew

java - Spring @Valid注解

php - imagecreatetruecolor因1536X1962而失败,但尺寸较小

javascript - 在 JavaScript 中的 Promises 中捕获 Promises 中生成的错误

jsf - 在两个不同的路径上配置相同的错误页面?

ruby-on-rails - 如何在使用 Cucumber 编写测试时验证 api 的响应

ruby-on-rails - 在未调用的辅助方法中打开 CSV 文件

iphone - iPhone客户端的表单验证逻辑和错误消息

javascript - 多个错误 DIV 的 JQuery 错误放置