2014-01-14 130 views
2

還有其他問題與此有關,但它們似乎都是< Rails 4,更重要的是,它們不是太詳細!使用rails共享模型驗證4

他們都談論創建一個模塊中分享這些共同驗證:

require 'active_record' 
module ContactValidations 
    def self.included(base_class) 
    base_class.class_eval do 
     include ContactValidations::InstanceMethods 
     # model validations 
     validates_presence_of(:name, :message => 'You must provide a company name.') 
     validates_presence_of(:street, :message => 'You must provide a company street.') 
     validates_presence_of(:city, :message => 'You must provide a company city.') 
     validates_presence_of(:post_code, :message => 'You must provide a company post code.') 

     validates_numericality_of(:telephone, :on => :create, :message => 'Telephone should be a number with no spaces.', :if => :telephone_given?)  
     validates_numericality_of(:area_code, :on => :create, :message => 'Telephone area code should be a number with no spaces.', :if => :area_code_given?) 

     validates_numericality_of(:fax, :on => :create, :message => 'Fax should be a number with no spaces.', :if => :fax_given?) 

     validates_numericality_of(:fax_area_code, :on => :create, :message => 'Fax area code should be a number with no spaces.', :if => :fax_area_code_given?) 

     validates_format_of(:web, :with => /^((http)?:\/\/)?(www\.)?([a-zA-Z0-9]+)(.[a-zA-Z0-9]{2,3})(\.[a-zA-Z0-9]{2,3})$/, :on => :create, :message => 'Web address is invalid. Example: http://www.domain or http://domain.', :if => :web_given?) 

     validates_format_of(:email, :with => /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/, :on => :create, :message => 'Th email address given is invalid.', :if => :email_given?) 

     validates_uniqueness_of(:email, :message => 'This email is already given.') 
    end 
    end 

    module InstanceMethods 
    def telephone_given? 
     !telephone.blank? 
    end 

    def fax_given? 
     !fax.blank? 
    end 
    def web_given? 
     !web.blank? 
    end 
    def email_given? 
     !email.blank? 
    end 
    def area_code_given? 
     !area_code.blank? 
    end 
    def fax_area_code_given? 
     !fax_area_code.blank? 
    end 

    end 
end 

但起碼我不知道在哪裏這樣的文件應該被保存。在lib目錄中? lib目錄中的所有文件都包括在內,似乎有點浪費了一個模塊,我只希望被包含在兩個或三個型號...

  1. 確實軌道4必須共享驗證一個內置的方式嗎?
  2. 如果不是,我應該在哪裏保存自定義模塊?
  3. 只需要非常清楚,我應該如何在需要包含這些驗證的模型中需要此模塊?

回答

0

app/models/concerns創建模塊,然後將它們包含在你的類:

include ContactValidations 

這樣Rails會自動加載共享的模塊,讓他們爲您提供包括。

+0

還應該擴展'ActiveSupport :: Concern'並將驗證放入'included'塊中:http://stackoverflow.com/a/11372578/1173020 –