我有一个 Order 模型,其中包含一个必需的 delivery_address 和一个可选的 billing_address。订单有一个布尔属性 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?是 true,并且 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 然后它告诉我它无法保存导致验证失败。
有任何想法吗?嵌套属性有点令人困惑。提前致谢!