# How to stop callbacks from getting called twice

**URL:** <https://www.ruby-forum.com/t/how-to-stop-callbacks-from-getting-called-twice/140441>\
**Category:** Rails\
**Created:** [June 14, 2008, 12:29am UTC](https://www.ruby-forum.com/t/how-to-stop-callbacks-from-getting-called-twice/140441 "2008-06-14T00:29:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kuma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/a587f6/32.png) [@kuma](https://www.ruby-forum.com/u/kuma)\
**Post date:** [June 14, 2008, 12:29am UTC](https://www.ruby-forum.com/t/how-to-stop-callbacks-from-getting-called-twice/140441/1 "2008-06-14T00:29:57Z")

</div>

Maybe this is old news, but it took me all afternoon:

In my test environment, an ‘after\_create’ callback was getting called  
twice unexpectedly. In my model, I had a simple ‘after\_create :foo’  
declaration.

From what I understand, the problem seems to be that the ‘after\_create  
:foo, :bar’ syntax appends those symbols to an array without doing a  
‘uniq’. It seems that if you happen to load the class twice, you’ll get  
double entries in the callback list. This can happen easily because the  
Ruby ‘require’ method doesn’t seem to convert paths to absolute paths,  
e.g the following will cause the file ‘/lib/foo.rb’ to be loaded twice:

# In \app\models\bar.rb

require File.join(RAILS\_ROOT, ‘lib’, ‘foo’)  
require ‘…/…/lib/foo’  
class Bar \< ActiveRecord::Base

end

So, I added this to my environment.rb:

module Callbacks  
def callbacks\_for\_with\_uniq(method)  
callbacks\_for\_without\_uniq(method).uniq  
end

alias\_method\_chain :callbacks\_for, :uniq  
end

- OR -

You could use the alternate form of defining a callback, but this is  
less convenient.

def after\_create

# …

end
