Search code examples
ruby-on-railsresque

Rails queue a calculation after_destroy


I'm in the process of implementing resque to recalculate some thing after a model instance is destroyed. To do this I'm using an after_destroy callback. Before I implement the calculation I want to test to ensure that the calculations will be executed on a different subset.

So to test this I am using rails c --sandbox and am getting some confusing information. Here is the output:

> @run = Run.new(status: 0, archived: false)
> @run.save 
> I then print the Run.count and get 200
> @run.destroy!
> I then print the Run.count and get 200

Note I'm using after_save and after_destroy to print out the Run.count numbers that are equal when I think they should be different.

My end goal is when certain conditions are changed add a calculation to a resque queue and continue on.

The main question I have is. Why aren't the number changed? Will the specific run be flagged for deletion and not included in my calculation query?


Solution

  • When a callback executes, it executes in a transaction. It may cause problems when you perform your calculations before the transaction ends. Try to use after_commit callback, which performs after the transaction ends.

    after_commit :do_something, on: :create
    after_commit :do_something, on: :destroy