开发者

Rails 3 manually creating model and persisting not working

So I have a model object that needs to insert packing slips if the model is saved (the model in question is for a payment).

I attempted to do this in the after_save hook for the Payment model, but it never actually persisted the packing slips. I moved this to the controller in the if @payment.save blah blah block, but it still will not persist the models. The code is below:

  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 !@order.has_membership?

Note that the MembershipMailer is firing so I know it's in there, but those packing slips will not persist. I attempt to replicate this functionality by hand in th开发者_JAVA百科e console and it works fine. Not sure what is stopping it. I have no validations in the PackingSlip model at the moment.


When you say it's not persisting, do you mean that the association isn't there, or that it's not being saved in the database?

One option (as Brian mentioned above) would be to add some debug logging to see exactly what's going on. I've taken the liberty of refactoring your code be more Rails-like (assuming that 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜