[英]Validate presence of shipping address unless it's same as billing address
I have this in my Order class. 我的Order类中有这个。 I want to validate the presence of
shipping_address
unless it's the same as the billing_address
. 我想验证
shipping_address
的存在,除非它与billing_address
相同。 My specs keep failing, however. 但是,我的规格一直在失败。
class Order < ActiveRecord::Base
attr_writer :ship_to_billing_address
belongs_to :billing_address, class_name: 'Address'
belongs_to :shipping_address, class_name: '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
end
def ship_to_billing_address?
self.ship_to_billing_address
end
end
But I keep getting failed specs (expected example not to be valid): 但是我一直在获取失败的规格(预期的示例无效):
describe "shipping_address_id" do
context "when shipping address is different from billing address" do
before { @order.ship_to_billing_address = false }
it_behaves_like 'a foreign key', :shipping_address_id
end
end
shared_examples 'a foreign key' do |key|
it "can't be nil, blank, or not an int" do
[nil, "", " ", "a", 1.1].each do |value|
@order.send("#{key}=", value)
@order.should_not be_valid
end
end
end
Form code: 表单代码:
= f.check_box :ship_to_billing_address
| Use my shipping address as my billing address.
Your ship_to_billing_address
method implementation is wrong. 您的
ship_to_billing_address
方法实现错误。 It sets @ship_to_billing_address
to true
even if was set to false
before. 它集
@ship_to_billing_address
到true
即使设置为false
之前。 This is more correct implementation: 这是更正确的实现:
def ship_to_billing_address
@ship_to_billing_address = true if @ship_to_billing_address.nil?
@ship_to_billing_address
end
Examples: 例子:
irb(main):001:0> class Order
irb(main):002:1> attr_writer :stba
irb(main):003:1> def stba
irb(main):004:2> @stba ||= true
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0>
irb(main):008:0* o = Order.new
=> #<Order:0x8bbc24c>
irb(main):009:0> o.stba = false
=> false
irb(main):010:0> o.stba
irb(main):011:0> class Order2
irb(main):012:1> attr_writer :stba
irb(main):013:1> def stba
irb(main):014:2> if @stba.nil?
irb(main):015:3> @stba = true
irb(main):016:3> else
irb(main):017:3* @stba
irb(main):018:3> end
irb(main):019:2> end
irb(main):020:1> end
=> nil
irb(main):021:0> o = Order2.new
=> #<Order2:0x8b737e0>
irb(main):022:0> o.stba = false
=> false
irb(main):023:0> o.stba
=> false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.