如何根据是否在Rails中选中复选框来验证attr?

时间:2013-05-08 20:55:23

标签: ruby-on-rails ruby validation

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

三个小时后,我没有办法解决这个问题......

1 个答案:

答案 0 :(得分:4)

默认情况下,check_box会返回一个字符串,因此'1''0'而不是10。在测试值时要记住这一点。这是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子对象还是属性?