2013-05-15 48 views
0

將地址和帳單地址提取到地址模型中缺少提示,如何刪除此驗證重複?如何從模型中刪除驗證重複?

我只想驗證帳單郵寄地址是否與收貨地址不同。我將如何去解壓縮到一個模塊?一個例子會非常有用,因爲我不知道模塊中包含什麼,或者self指的是。

validates :shipping_name, :shipping_address1, :shipping_street_number, :shipping_city, presence: true 
    validates :shipping_state, inclusion: { in: Address.states.values } 
    validates :shipping_post_code, length: { is: 5 }, numericality: { only_integer: true } 

    validates :billing_name, :billing_address1, :billing_street_number, :billing_city, presence: true, unless: -> { self.bill_to_shipping_address? } 
    validates :billing_state, inclusion: { in: Address.states.values }, unless: -> { self.bill_to_shipping_address? } 
    validates :billing_post_code, length: { is: 5 }, numericality: { only_integer: true }, unless: -> { self.bill_to_shipping_address? } 

回答

1

您可以創建一個方法,然後傳遞兩種地址之間不同的位。在這種情況下,區別在於字段的前綴字以及傳遞額外選項的能力。

module AddressValidator 
    def validates_address(type, options = {}) 
    validates :"#{type}_name", :"#{type}_address1", :"#{type}_street_number", :"#{type}_city", {presence: true}.merge(options) 
    validates :"#{type}_state", {inclusion: { in: Address.states.values }}.merge(options) 
    validates :"#{type}_post_code", {length: { is: 5 }, numericality: { only_integer: true }}.merge(options) 
    end 
end 

class MyModel < ActiveRecord::Base 
    extend AddressValidator 
    validates_address(:shipping) 
    validates_address(:billing, unless: -> { self.bill_to_shipping_address? }) 
end 
+0

謝謝。我現在必須問自己是否值得。 – dee