Rails回调未执行

4

我一直在寻找原因,为什么我的回调有时候没有被执行(没错,你听到了,有时候会出现这种情况,但大多数情况下都可以正常工作)。这与两个模型之间的父/子关系有关。

在创建子记录时,在after_create回调中,我所做的全部工作就是更新(累加所有子记录的金额以避免运行时进行繁重的查询)父表/模型记录中的金额字段。

父模型(Payout

子模型是(Sales Transaction

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

因此,Payout的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

这里有趣的部分是,有时候当创建SalesTransaction时,回调函数就不会被调用,因为我没有看到payouts记录中的更新值。 我现在试图避免回调,但为了知道为什么回调没有执行,我提出了这个问题。
注意:
1. SalesTransaction和Payout表上都没有验证(我检查了1000次) Payout.validators => [] SalesTransaction.validators => []
2. 没有批量赋值问题,因为我没有定义attr_accessible或attr_protected(我也检查过,并且正常工作,否则就会出现批量赋值警告)
3. SalesTransaction记录一直在创建,只有payouts记录没有更新(有时候)。
4. 我已经从sales_transactions和payouts中删除了大部分不必要的关联,以简化代码。
5. 模型中没有像accepts_nested_attributes_for这样的东西。
6. 没有动态验证。
最后,这是我如何创建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)


我注意到的第一件事情是Payout类没有继承自ActiveRecord::Base。此外,我对注释#2感到困惑。您是否在您的application.rb文件中禁用了白名单属性,这就是为什么您没有使用attr_accessible的原因?否则,这些属性列表需要被定义。如果这两个问题不是罪魁祸首,那么这应该可以工作,因为我刚刚测试过了。 - Keith
@Keith,我道歉,是打错字了,已经更正过来了。 - Ratatouille
@Keith 关于白名单,正如我所提到的,我在 Payout 模型中没有定义任何 attr_accessibleattr_protected,并且在同一点中提到,这是一个批量赋值的情况,如果出现问题,它会一直失败而不是有时候。 - Ratatouille
2个回答

0
我想回复 Viren 的评论。请尝试使用 SalesTransaction.create!(加上感叹号)。你是否一直看到批量赋值错误?

不对,销售交易记录已经被创建了,只是赔付列的“更新”功能没有起作用,“有时候”。我已经检查了赔付模型中的批量分配。 - Ratatouille

0
尝试使用 after_save 而不是 after_create。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接