【发布时间】:2016-03-07 20:06:30
【问题描述】:
以下是我的应用中发生的情况:
- 客户输入电话号码
- 在客户模型中搜索电话号码以查看是否存在
- 如果确实存在,请转到客户展示页面
- 如果不存在,进入客户新页面创建新客户
据我了解,模型验证是针对在数据库中输入/编辑/删除的数据。
但是,我们如何在数据库中进行任何搜索之前检查(使用验证)?如果它不正确(例如:使用字母而不是数字作为电话号码),那么将显示错误。
我正在实现 html 表单输入选项,以防止有人在电话号码输入框中输入字母,如下所示:
<%= form_tag(new_customer_path, method: :get) do %>
<%= telephone_field_tag :phone, nil, placeholder: "Phone Number", required: true, pattern: "[0-9]{10}", title: "Number must be 10 digits", maxlength: "10", class: "input-lg" %>
<%= submit_tag "Enter", class: "btn btn-primary btn-lg" %>
<% end %>
但是我的表单变得越来越大,因为我会将 html 表单输入框选项放在所有内容(电话、邮政编码、电子邮件等)上。
什么是更合适的“Rails”方式?使用活动记录验证来显示错误,或者提供 html 表单输入选项来预先验证数据?还是两者的结合(最大安全?客户端和数据库之前)?
型号
class Customer < ActiveRecord::Base
validates_presence_of :first_name, :last_name, :phone, :email, :zip_code
validates_uniqueness_of :phone, :email
validates :phone, :zip_code, :numericality => {:only_integer => true}
validates_length_of :phone, is: 10
validates_length_of :zip_code, is: 5
end
控制器
def new
if @customer = Customer.find_by(phone: params[:phone])
flash[:success] = "Welcome back"
redirect_to @customer
else
@customer = Customer.new(phone: params[:phone])
flash.now[:warning] = "Customer not found, please sign up!"
end
end
部分错误信息
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>">
<a href="#" data-dismiss="alert" class="close">×</a>
<ul>
<li>
<p><%= value %></p>
</li>
</ul>
</div>
<% end %>
【问题讨论】:
标签: ruby-on-rails validation rails-activerecord