Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip ActiveRecord callbacks? [duplicate]

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?

like image 509
Jakub Arnold Avatar asked Aug 27 '09 18:08

Jakub Arnold


4 Answers

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

like image 160
tardate Avatar answered Oct 30 '22 02:10

tardate


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
like image 26
sheldonh Avatar answered Oct 30 '22 02:10

sheldonh


For Rails 2, but not Rails 3 you can use these:

object.send(:create_without_callbacks)
object.send(:update_without_callbacks)
like image 29
Stan Bright Avatar answered Oct 30 '22 02:10

Stan Bright


This will skip your validations:

vote.save(:validate => false)

more info here

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.

like image 28
workdreamer Avatar answered Oct 30 '22 01:10

workdreamer