A gotcha

February 27th, 2008

Just got bitten by this. Observers are not called when deleting an object via a through collection.

An example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Newsletter < ActiveRecord::Base
  has_many :subscribers
  has_many :users, :through => :subscribers
end

class SubscriberObserver <  ActiveRecord::Observer
  def after_destroy(subscriber)
    # do somethng
  end
end

# case 1
# deletes a subscriber object. after_destroy is not called
@newsletter.users.delete(user) 

# case 2
 # after_destroy is called.
subscriber = @newsletter.subscribers.find(:first, :conditions => ["user_id = ?", user.id])
subscriber.destroy unless subscriber.nil?  

In both cases a subscriber object is being destroyed, but the observer is being called only in the second scenario. I'll have to look into patching this when I get a chance ....

Sorry, comments are closed for this article.