我有一个为通讯簿创建新联系人的表单。在模型中,需要first_name和last_name字段:
型号/联系人.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
以下是尝试提交无效请求后的网页图像:
显示错误的网络选项卡视图
Contact.new
初始化新的Contact
对象,但不验证或存储它。
调用valid?
或invalid?
进行验证。这会将错误添加到记录中。如果对它调用save
(或save!
(,它还会在存储记录之前运行验证。