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。
後三小時,我出去的方式固定這...
謝謝!我只是意識到,我需要在'accep_nested_attributes_for'上使用'reject_if:condition',否則它們的驗證將始終啓動。這使得它更復雜一點... – Mohamad 2013-05-08 21:28:03
它是'Order belongs_to:shipping_address'和相同的帳單地址。 ..都映射到'地址' – Mohamad 2013-05-08 21:28:57
不會'ship_to_billing_address>'0''引發一個參數錯誤比較一個fixnum和一個字符串? – Mohamad 2013-05-08 21:41:36