2011-02-09 37 views
0

所以我有一個模型對象需要插入裝箱單,如果保存模型(所涉及的模型是爲了付款)。Rails 3手動創建模型並堅持不工作

我試圖在支付模式的after_save掛鉤中執行此操作,但它實際上從未實際上持續存在裝箱單。我把它移到了if @ payment.save等等塊的控制器中,但它仍然不會持續模型。代碼如下:

if @payment.save 

    if @payment.order.has_physical_product? 
     # generate packing slip for shipping 
     slip = PackingSlip.new(:payment_id => @payment.id, :department => "Shipping") 
     slip.save! 

     if @payment.order.has_book? 
     slip = PackingSlip.new(:payment_id => @payment.id, :department => "Royalty") 
     slip.save! 
     end 

    end 

    MembershipMailer.membership_email(@order) unless [email protected]_membership? 

注意,MembershipMailer被解僱,所以我知道它在那裏,但這些裝箱單不會持續。我試圖在控制檯中手動複製這個功能,並且它工作正常。不知道是什麼阻止它。我目前在PackingSlip模型中沒有驗證。

+0

把一些記錄。最明顯的是`@ payment.order.has_physical_product?`返回false。 – 2011-02-09 03:25:47

回答

1

當你說它不是持久的時候,你的意思是該關聯不存在,或者它沒有被保存在數據庫中?

一個選項(如上面提到的Brian)將添加一些調試日誌記錄來查看到底發生了什麼。我已經採取了重構你的代碼更加的Rails般的自由(假設payment has_many :packing_slips):

class Payment < ActiveRecord::Base 
    has_many :packing_slips 
    after_save :generate_packing_slips 

    def generate_packing_slips 
    if order.has_physical_product? 
     packing_slips.create(:department => "Shipping") 
     packing_slips.create(:department => "Royalty") if order.has_book? 
    end 

    # At this point, the packing_slips collection should be 
    # populated - valid or not, so we can check what's going on. 
    # If you're not getting any output here, the packing slips 
    # aren't even being generated, which means there's a problem 
    # with order.has_physical_product? 

    if Rails.env.development? 
     packing_slips.each do |ps| 
     Rails.logger.debug("Error Messages: #{ps.errors.full_messages.inspect}") unless ps.valid? 
     end 
    end 

    # btw, `unless !foo` is the same as `if foo` 
    MembershipMailer.membership_email(order) if order.has_membership? 
    end 
end