2

I would like to skip/disable ActiveRecord callbacks in, specifically, Rails 3. The following is an example solution I thought of -- creating an attribute that is defined to create the object without callbacks.

product = Product.new(title: 'Smth')
product.send(:create_without_callbacks)

The above example is similar to that in this answer, but the author said it is for specifically Rails 2. Is there a similar, or even better, way to do this for Rails 3?

Community
  • 1
  • 1
xpepermint
  • 35,055
  • 30
  • 109
  • 163

3 Answers3

1
  1. See the question: How can I avoid running ActiveRecord callbacks?
  2. This blog post has another explanation with example.
Community
  • 1
  • 1
Kyle Heironimus
  • 7,741
  • 7
  • 39
  • 51
  • The blog post mentioned a solution for Rails 3. The private create_without_callbacks method was removed in Rails 3. Have you consider putting an exception in your callbacks? – Kyle Heironimus Dec 20 '10 at 20:12
  • Hum... I would like to disabled it "per instance"/"per process". The blog explains how to disable it globally. – xpepermint Jan 23 '11 at 10:21
  • @xpepermint the blog post I linked to in my answer shows another solution. It will work for Rails 3 AND 4. – onebree Aug 20 '15 at 19:17
0

You may find the solution here helpful: http://manuelvanrijn.nl/blog/2012/01/12/disable-rails-before-slash-after-callback/

TL;DR - If you are doing this production, it may be helpful to create a class (see blog post) to keep your code DRY. Otherwise, if you do this once, or even in testing (like myself), you can simply do the following:

SomeModel.skip_callback(:save, :before, :before_action)
SomeModel.skip_callback(:save, :after, :after_action)

The blog post provides a nice list of callbacks the above method will work with.

This will work in both Rails 3 and Rails 4. As noted by a comment, if you have to disable callbacks, you may want to ask yourself why you need those callback. To expand, disabling callbacks are questionable only in production. If you need to disable them in testing (which is what I am doing myself), it is acceptable... Especially since Rails 4 core deprecated the use of observers.

Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
onebree
  • 1,853
  • 1
  • 17
  • 44
-1
SomeModel.skip_callback(:save) do 
   somemodel_instance.save
end

tested: Rails 4.2.1

Nijeesh Joshy
  • 1,426
  • 13
  • 24
Zen
  • 382
  • 3
  • 9