0

我想验证 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,验证仍在启动。

三个小时后,我无法解决这个问题......

4

1 回答 1

4

默认情况下,check_box返回一个字符串,所以'1'or'0'而不是1or 0。测试值时请记住这一点。这是文档

我也可能会更改attr_writertoattr_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子对象还是只是属性?

于 2013-05-08T21:26:26.263 回答