rails回调没有被执行

时间:2013-07-30 18:51:46

标签: ruby-on-rails activerecord ruby-on-rails-3.2 rails-activerecord

对于我的生活,我试图找出为什么我的回调没有被执行sometimes(你听到它正确有时,因为大部分时间它开箱即用)

我所拥有的只是2个模型之间的父/子关系

在创建子记录时,我在after_create回调中所做的全部是更新(在父字段中累积所有子数量以避免在运行时重度查询)父表/模型记录中的金额字段

父模型(Payout

儿童模型是(Sales Transaction

Payout has_many SalesTransactions如上所述,在创建销售交易时,我正在更新(准确地增加)父记录的amount字段(支付记录)以避免在运行时进行大量查询。

因此,付款amount field只是对该付款的sales_transactions的所有金额的总和

和payout.amount一样好(在执行回调之后)

payout.amount == payout.sales_transactions.pluck('amount').sum

我尝试使用回调实现的目标

class SalesTransaction < ActiveRecord::Base
   belongs_to :payout
   after_create :update_payout_for_sale

   def update_payout_for_sale
    sales_amount = payout.amount || 0
    sales_amount =  sales_amount + amount.to_f
    ## Also make note of the minus from original amount i.e refund and custom_deduction_amount
    payout.update_attributes(:amount => sales_amount)
  end  

end

class Payout < ActiveRecord::Base
  has_many :sales_transactions
  has_one :referrer
  after_save :update_referrer_earning

  def update_referrer_earning
    referrer.update_attributes(:amount  => (amount*10)/100.to_d)) rescue nil
  end
end

这里有趣的部分是sometime当SalesTransaction为created时,回调未被调用,因为我没有看到支付记录的更新值

我现在正试图避免回调但是为了知道why回调没有被执行,led me提出这个问题

  1. SalesTransaction和Payout表上都没有验证(我已经检查了1000次) Payout.validators =&gt; []

    SalesTransaction.validators =&gt; []

  2. 没有质量分配问题,因为我没有定义attr_accessibleattr_protected(我也检查过这个问题,并且说它工作时间大部分时间不会出现这种情况质量分配警告)

  3. SalesTransaction记录一直在创建,只有支付记录未获得更新(sometime

  4. 我已从sales_transactionspayouts删除了大部分不需要的(此处)关联 代码简洁

  5. 在任何一个模型上都没有accepts_nested_attributes_for之类的东西

  6. 未附加动态验证,额外,额外

  7. 最后,我在这里尝试创建SalesTransaction

      options =  {"performer_id"=>177, "customer_id"=>35526, "sale_type"=>"sale", "show_id"=>502, "performer_percentage"=>BigDecimal.new("40.0"), "show_duration"=>4104, "gross_credits"=>3754, "gross_sales"=>BigDecimal.new("375.4"), "amount"=>BigDecimal.new("150.16"), "affiliate_id"=>nil, "affiliate_earning"=>BigDecimal.new("0.0"), "total_profit"=>BigDecimal.new("225.24"), "payout_period_id"=>89,"payout_id"=>4156, "stream_connection_id"=>540572, "history_id"=>44575, "credits"=>{:when_show_started=>350, :purchased_during_show=>{:free=>[], :paid=>[]}, :total_consumed=>{:free=>350, :paid=>3754}}, "sliding_scale_recalculations_done"=>false, "paid_minutes"=>62.57}
    

    SalesTransaction.create(options)

2 个答案:

答案 0 :(得分:0)

我想回应Viren发表评论。试试SalesTransaction.create!(带感叹号)。那么你是否一直看到质量分配错误?

答案 1 :(得分:0)

尝试使用after_save而不是after_create。