How to skip ActiveRecord callbacks?
Ruby on-RailsRails ActiverecordRuby on-Rails Problem Overview
> Possible Duplicate:
> How can I avoid running ActiveRecord callbacks?
I have model like this
class Vote < ActiveRecord::Base
after_save :add_points_to_user
.....
end
Is it possible to somehow force model to skip calling add_points_to_user
when saved? Possibly something like ActiveRecord#delete
vs ActiveRecord#destroy
?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
For Rails 3, ActiveSupport::Callbacks gives you the necessary control. I was just facing the same challenge in a data integration scenario where normally-desirable-callbacks needed to be brushed aside. You can reset_callbacks en-masse, or use skip_callback to disable judiciously, like this:
Vote.skip_callback(:save, :after, :add_points_to_user)
..after which you can operate on Vote instances with :add_points_to_user inhibited
Solution 2 - Ruby on-Rails
The following applies to rails 2, rails 3 and rails 4:
http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html#skipping-callbacks
It provides a list of methods that skip callbacks, explaining why it is dangerous to use them without careful consideration. Reprinted here under the provisions of the Creative Commons Attribution-Share Alike 3.0 License.
> 12 Skipping Callbacks > > Just as with validations, it is also possible to skip callbacks. These > methods should be used with caution, however, because important > business rules and application logic may be kept in callbacks. > Bypassing them without understanding the potential implications may > lead to invalid data. > > - decrement > - decrement_counter > - delete > - delete_all > - find_by_sql > - increment > - increment_counter > - toggle > - touch > - update_column > - update_all > - update_counters
Solution 3 - Ruby on-Rails
For Rails 2, but not Rails 3 you can use these:
object.send(:create_without_callbacks)
object.send(:update_without_callbacks)
Solution 4 - Ruby on-Rails
This will skip your validations:
vote.save(:validate => false)
more info http://guides.rubyonrails.org/active_record_validations_callbacks.html#running-callbacks">here</a>
To skipping your callbacks and validations, you can use, update_column v(3.1), or update_all
vote = Vote.first
vote.update_column(:subject, 'CallBacks')
Aparentlly this only works with ActiveRecord 3.1
Or:
Vote.where('id = ?', YourID).update_all(:subject => 'CallBacks')
In the end you have also i finally option and this will skip everthing:
execute "UPDATE votes SET subject = 'CallBacks' WHERE id = YourID"
OK the last one it's not so pretty.