How can I avoid running ActiveRecord callbacks?
Use update_column
(Rails >= v3.1) or update_columns
(Rails >= 4.0) to skip callbacks and validations. Also with these methods, updated_at
is not updated.
#Rails >= v3.1 only@person.update_column(:some_attribute, 'value')#Rails >= v4.0 only@person.update_columns(attributes)
http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column
#2: Skipping callbacks that also works while creating an object
class Person < ActiveRecord::Base attr_accessor :skip_some_callbacks before_validation :do_something after_validation :do_something_else skip_callback :validation, :before, :do_something, if: :skip_some_callbacks skip_callback :validation, :after, :do_something_else, if: :skip_some_callbacksendperson = Person.new(person_params)person.skip_some_callbacks = trueperson.save
UPDATE (2020)
Apparently Rails has always supported :if
and :unless
options, so above code can be simplified as:
class Person < ActiveRecord::Base attr_accessor :skip_some_callbacks before_validation :do_something, unless: :skip_some_callbacks after_validation :do_something_else, unless: :skip_some_callbacksendperson = Person.new(person_params)person.skip_some_callbacks = trueperson.save
This solution is Rails 2 only.
I just investigated this and I think I have a solution. There are two ActiveRecord private methods that you can use:
update_without_callbackscreate_without_callbacks
You're going to have to use send to call these methods. examples:
p = Person.new(:name => 'foo')p.send(:create_without_callbacks)p = Person.find(1)p.send(:update_without_callbacks)
This is definitely something that you'll only really want to use in the console or while doing some random tests. Hope this helps!
Updated:
@Vikrant Chaudhary's solution seems better:
#Rails >= v3.1 only@person.update_column(:some_attribute, 'value')#Rails >= v4.0 only@person.update_columns(attributes)
My original answer :
see this link: How to skip ActiveRecord callbacks?
in Rails3,
assume we have a class definition:
class User < ActiveRecord::Base after_save :generate_nick_nameend
Approach1:
User.send(:create_without_callbacks)User.send(:update_without_callbacks)
Approach2: When you want to skip them in your rspec files or whatever, try this:
User.skip_callback(:save, :after, :generate_nick_name)User.create!()
NOTE: once this is done, if you are not in rspec environment, you should reset the callbacks:
User.set_callback(:save, :after, :generate_nick_name)
works fine for me on rails 3.0.5