# ActiveRecord::Observer, update\_all and has\_many

**URL:** <https://www.ruby-forum.com/t/activerecord-observer-update-all-and-has-many/191571>\
**Category:** Rails\
**Created:** [July 14, 2010, 5:11pm UTC](https://www.ruby-forum.com/t/activerecord-observer-update-all-and-has-many/191571 "2010-07-14T17:11:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![reggieb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/3e96dc/32.png) [@reggieb](https://www.ruby-forum.com/u/reggieb)\
**Post date:** [July 14, 2010, 5:11pm UTC](https://www.ruby-forum.com/t/activerecord-observer-update-all-and-has-many/191571/1 "2010-07-14T17:11:20Z")

</div>

Hi,

I’m using an ActiveRecord::Observer to log users changing data in my  
application. However, I’ve noted that adding an item to a has\_many  
relationship gets logged, but removing the item does not. That is:

@product.users \<\< user

is logged, but:

@product.users.delete(user)

is not.

I’ve dug into ActiveRecord and found that the underlying issue is that  
the HasManyAssociation delete\_records method uses update\_all to update  
the record. update\_all bypasses the normal call backs and therefore also  
bypasses the Observer.

Is there a way to get an Observer to observe update\_all calls?

---

<div class="post-metadata">

**Author:** ![reggieb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/3e96dc/32.png) [@reggieb](https://www.ruby-forum.com/u/reggieb)\
**Post date:** [July 15, 2010, 1:07pm UTC](https://www.ruby-forum.com/t/activerecord-observer-update-all-and-has-many/191571/2 "2010-07-15T13:07:01Z")

</div>

I’ve worked out a solution. It might not be the neatest, but it works  
for me:

has\_many has its own call backs. So I can trigger a logging activity  
using the ‘after\_remove’ call back like this:

has\_many :users, :after\_remove =\> :log\_removal

I am then able to grab the Observe object using ObjectSpace:

def get\_an\_active\_activity\_logger  
active\_loggers = Array.new  
ObjectSpace.each\_object(ActivityLogger){|l| active\_loggers \<\< l}  
@activity\_logger = active\_loggers.first  
end

And call one of @activity\_logger’s public methods to generate the log.

def log\_removal(item)  
get\_an\_active\_activity\_logger  
@activity\_logger.log\_activity(  
self,  
‘item\_removal’,  
“#{item.class.name} #{item.id} removed from association”  
)  
end

It means I have to update each of my has\_many calls and make the  
log\_removal and get\_an\_active\_activity\_logger methods available to the  
models where they are needed, but both of those are fairly trivial  
tasks.
