1

I used to be able to register a before_destroy callback for every ActiveRecord instance in my app via the following code in ./config/initializers/active_record_base.rb ...

class ActiveRecord::Base
    before_destroy :enumerate_descendants

    def enumerate_descendants(args={})
        # code...
    end
end

But now, in a Rails 3.2.9 and ruby 1.9.3p327 app, this only works in development mode and not production. (From my controller I am calling destroy and not delete, btw.) Some proof:

localhost:my_app me$ RAILS_ENV=development rails console
Loading development environment (Rails 3.2.9)
1.9.3-p327 :001 > Person._destroy_callbacks
 => [<ActiveSupport::Callbacks::Callback:0x007fbdde8f2890 @klass=ActiveRecord::Base, @kind=:before, 
@chain=[...], @per_key={:if=>[], :unless=>[]}, @options={:if=>[], :unless=>[]},
@raw_filter=:enumerate_descendants, @filter=:enumerate_descendants, @compiled_options="true", @callback_id=12>] 

localhost:my_app me$ RAILS_ENV=production rails console
Loading production environment (Rails 3.2.9)
1.9.3-p327 :001 > Person._destroy_callbacks
 => [] 

If I use config.cache_classes = false in ./environments/production.rb, the callback is registered in production mode, but that's obviously a problem for a production app...

So, any ideas -- other than a base class for all my models -- how I can get a before_destroy callback registered for all instances of ActiveRecord in production mode?

Thanks!

1
  • Can it be that your models are loaded before you open ActiveRecord::Base and define the callback? When config.cache_classes is false your "extension" of ActiveRecord::Base is not done again, and because of that it's there when the models are reloaded.
    – 244an
    Dec 3, 2012 at 10:26

1 Answer 1

1

As I wrote in my comment, this is probably because your models are loaded before you add the "before_destroy" in ActiveRecord::Base. In development environment (when config.cache_classes = false) the models are reloaded (for every request?), and then the "before_destroy" is already registered on ActiveRecord::Base.

I have tested this in an old Rails, but I got the same behaviour

You must find out where to use the code for register the "before_destroy" on ActiveRecord::Base so it's done before any model are loaded.

If you test this yourself with e.g. doing require 'one_of_your_models' in console to see if it works with reload, that is not enough, you must do Object.send(:remove_const, :OneOfYourModels) before the reload (Rails are doing that before the reload of the models).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.