我有一个订单型号,其中has_one需要delivery_address和一个可选的billing_address。 Order有一个bool属性has_billing_address。在我的表单中,我接受嵌套属性:
class Order < ActiveRecord::Base
has_one :delivery_address, dependent: :destroy
has_one :billing_address, dependent: :destroy
accepts_nested_attributes_for :delivery_address, allow_destroy: true
accepts_nested_attributes_for :billing_address, allow_destroy: true
end
现场存在的两种地址模型都有验证。我只想在@ order.has_billing_address中创建billing_address?如果为结算地址,则还应触发billing_address上的验证。
我的订单控制器如下所示:
def address
if session['order_id'].blank?
@order = Order.new
@order.delivery_address = DeliveryAddress.new
@order.billing_address = BillingAddress.new
else
@order = Order.find(session['order_id'])
##### PROBLEM fails cause of validation:
@order.billing_address = BillingAddress.new if @order.billing_address.blank?
end
end
def process_address
has_billing_address = params[:order][:has_billing_address].to_i
params[:order].delete(:billing_address_attributes) if has_billing_address.zero?
if session['order_id'].blank?
@order = Order.new(params[:order])
@order.billing_address = nil if has_billing_address.zero?
@order.cart = session_cart
if @order.save
session['order_id'] = @order.id
redirect_to payment_order_path
else
render "address"
end
else
@order = Order.find(session['order_id'])
@order.billing_address = nil if has_billing_address.zero?
if @order.update_attributes(params[:order])
redirect_to payment_order_path
else
render "address"
end
end
end
我真的坚持这个 - 如果@ order.has_billing_address,应该没有对billing_address进行验证?是假的 - 我不能在BillingAddress模型的验证中使用if proc,因为有时候没有与模型关联的顺序。如果订单已经存在并且未设置帐单地址,则返回操作地址时还有另一个问题我必须再次显示嵌套的帐单地址表单,因此我调用@ order.billing_address = BillingAddress.new然后它告诉我它无法保存导致验证失败。
有什么想法吗?它与嵌套属性有点混淆。提前谢谢!
答案 0 :(得分:1)
在您的帐单邮寄地址模型中尝试使用此验证:
validate :field_name, :presence => true, :if => 'order.has_billing_address?'
编辑(尝试使用Proc):
validate :field_name, :presence => true, if: Proc.new { |c| c.order.has_billing_address?}
由于