2011-02-09 45 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