2013-05-08 40 views
0

我想驗證shipping_address的存在性,除非它與帳單地址相同。我爲它寫了一個attr_writer。我想用這個attr進行初始化。如何根據Rails中是否選中複選框來驗證attr?

class Order < ActiveRecord::Base 
    attr_writer :ship_to_billing_address 
    accepts_nested_attributes_for :billing_address, :shipping_address 

    validates :shipping_address, presence: true, unless: -> { self.ship_to_billing_address? } 

    def ship_to_billing_address 
    @ship_to_billing_address = true if @ship_to_billing_address.nil? 
    @ship_to_billing_address 
    end 

    def ship_to_billing_address? 
    ship_to_billing_address 
    end 
end 

這裏的形式:

# Use my shipping address as billing address. 
= f.check_box :ship_to_billing_address 

這是不行的,但是。表單提交0和1的值。所以我改變了方法,以這樣的:

def ship_to_billing_address? 
    ship_to_billing_address == 1 ? true: false 
    end 

然後向該只是爲了看看驗證仍然踢,但他們還是做...

def ship_to_billing_address? 
    true 
    end 

但驗證在即使仍然踢它返回false。

後三小時,我出去的方式固定這...

回答

4

默認情況下,check_box返回一個字符串,所以'1''0'而非10。在測試這個值時記住這一點。這是documentation

我也可能改變attr_writerattr_accessor並跳過其他方法,所以像

class Order < ActiveRecord::Base 
    attr_accessible :ship_to_billing_address 
    accepts_nested_attributes_for :billing_address, :shipping_address 

    validates :shipping_address, presence: true, 
           unless: -> { ship_to_billing_address > '0' } 
end 

我也不能確定accepts_nested_attributes_for電話 - 是:billing_address:shipping_address子對象或只是屬性?

+0

謝謝!我只是意識到,我需要在'accep_nested_attributes_for'上使用'reject_if:condition',否則它們的驗證將始終啓動。這使得它更復雜一點... – Mohamad 2013-05-08 21:28:03

+0

它是'Order belongs_to:shipping_address'和相同的帳單地址。 ..都映射到'地址' – Mohamad 2013-05-08 21:28:57

+0

不會'ship_to_billing_address>'0''引發一個參數錯誤比較一個fixnum和一個字符串? – Mohamad 2013-05-08 21:41:36