Problems with after_save callback

I have an object (call it an ‘emitter’), that has_many ‘emissions’
objects.

Each time I save an emission for a certain emitter, I need to do work
on the entire set of emissions for that emitter, including the new
emission.

I do this work in the emissions after_save handler. My problem arises
because, per the rails documentation, the newly saved emission is not
actually saved until after the after_save returns.

Trying to be clever, before doing anyhting else in the after_save
handler, I just pushed the newly saved emission onto the list of
emissions in memory:
emitter.emissions << self

So - that works just great, as long as I never reload the emitter’s
emissions (emitter.reload). If I do, then my new emission is gone.

Is there any way to force the new emission to really save in the
database before the after_save handler completes?

Thanks,
Yoram

Could you use an Observer instead? Or perhaps do the reverse and have
the after_save of the emission call update_totals with its emitter?

Cheers
Luke

Thansk Luke. I’m not familiar with observers but will research them.
Not yet knowing exactly what they are, I liked the fact that the
after_save handler guarantees that all the after_save processing will
be completed in the same thread as the save itself, thus avoiding the
potential for any race conditions in a multi-threaded environment.

As for your second suggestion - if I understand it correctly, that is
in fact what I am doing. The emission’s after save handler calls
emitter.update_emitter_emissions, which then runs through the entire
list of emissions, making changes as necessary. But that doesn’t
eliminate the problem… Or did I misunderstand your suggestion here?

Yoram B. wrote:

As for your second suggestion - if I understand it correctly, that is
in fact what I am doing. The emission’s after save handler calls
emitter.update_emitter_emissions, which then runs through the entire
list of emissions, making changes as necessary. But that doesn’t
eliminate the problem… Or did I misunderstand your suggestion here?

Yep, you are correct, sorry my mistake.

I’m off out now, but try looking at observers - will have a think about
this when I get back.

Cheers
Luke