我想验证 a 的存在,shipping_address
除非它与帐单地址相同。我attr_writer
为它写了一篇。我想用这个属性检查的对象进行初始化。
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,验证仍在启动。
三个小时后,我无法解决这个问题......