2013-08-29 77 views
0

我有一個訂單模型has_one需要delivery_address和一個可選的billing_address。 Order有一個bool屬性has_billing_address。在我的表單中,我接受嵌套屬性:rails has_one關係條件嵌套屬性驗證

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 

在兩種地址模型上都存在針對現場存在的驗證。我只想創建billing_address,如果@ order.has_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沒有驗證?是錯誤的 - 我無法使用if proc來驗證BillingAddress模型,因爲有時候模型沒有關聯的順序。如果訂單已經存在並且沒有設置帳單地址,則返回到操作地址還有另一個問題,我必須再次顯示嵌套帳單地址表單,因此我打電話給@ order.billing_address = BillingAddress.new然後它告訴我它不能被保存導致驗證失敗。

任何想法?這與嵌套屬性有點混淆。提前致謝!

回答

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?} 

感謝

+0

感謝您的快速回復。如果驗證是這樣的,驗證不會被觸發。 – Oliver

+0

更新了我的答案。它應該工作。 –

+0

確定驗證被觸發,但是當沒有訂單存在可能是我的情況:獲取未定義的方法'has_billing_address?'對於零:NilClass – Oliver