2016-03-07 113 views
0

這裏是我的應用程序會發生什麼:軌動作之前驗證

  • 顧客進入
  • 電話號碼搜索客戶模型,看看它,如果它存在,它存在
  • 電話號碼,請訪問客戶展示
  • ,如果它不存在,去爲客戶新的頁面來創建新的客戶

據我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 %> 

回答

0

只需在JavaScript和HTML中添加前端驗證即可。你的Rails驗證看起來很好。

Html:required屬性。

Jquery:查看此鏈接 - http://jqueryvalidation.org/