无效的创建方法不会引发任何错误

时间:2020-09-28 09:45:55

标签: ruby-on-rails validation error-handling

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

models / 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" %>
    [...]

当我输入缺少名字或姓氏的联系人时,不会创建该联系人,并且页面停留在表单上。但是,视图顶部不会出现任何错误。我在控制器中添加了一些调试功能,发现尽管提交无效,但没有创建任何错误:

controllers / 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 据我所知,我在模型中的验证是正确的,并且提交被识别为无效,但是由于某种原因,这不会转换为错误。我需要更改什么?

任何帮助都将非常棒!谢谢您的光临。

编辑:

这是完整的创建方法,其中包括.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

1 个答案:

答案 0 :(得分:1)

Contact.new初始化一个新的Contact对象,但不对其进行验证或存储。

致电valid?invalid?进行验证。这会将错误添加到记录中。如果您在其上调用save(或save!),它还将在存储记录之前运行验证。