我想验证shipping_address
的存在,除非它与帐单邮寄地址相同。我为它写了attr_writer
。我想用这个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,验证仍在继续。
三个小时后,我没有办法解决这个问题......
答案 0 :(得分:4)
默认情况下,check_box
会返回一个字符串,因此'1'
或'0'
而不是1
或0
。在测试值时要记住这一点。这是documentation。
我也可能会将attr_writer
更改为attr_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
子对象还是属性?