这里是我的应用程序会发生什么:轨动作之前验证
- 顾客进入
- 电话号码搜索客户模型,看看它,如果它存在,它存在
- 电话号码,请访问客户展示 页
- ,如果它不存在,去为客户新的页面来创建新的客户
据我understandi ng,模型验证适用于输入/编辑/删除到数据库中的数据。
但是,如何在数据库中进行任何搜索之前检查(使用验证)?如果不正确(例如:使用字母而不是数字代表电话号码),则会显示错误。
我正在执行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 %>