9

I have an auction and a bid object in my application, when someone presses the BID BUTTON it then calls the BID CREATE controller which created the bid, and then does some other things on the auction object:

BIDS CONTROLLER -> CREATE

@auction.endtime += @auction.auctiontimer
@auction.winner = @auction.arewinning 
@auction.save

AUCTION MODEL

before_update :set_endtime

def set_endtime
   self.endtime=self.starttime+self.auctiontimer
end

So the question is: How can C skip the "before callback" only, in this specific @auction.save

Hoberfinkle
  • 35
  • 1
  • 7
Yassine S.
  • 1,061
  • 1
  • 13
  • 22
  • so you don't want to execute the callback if it is a new record? or does it depend on the action? – phoet Oct 18 '13 at 12:22
  • possible duplicate of [How can I avoid running ActiveRecord callbacks?](http://stackoverflow.com/questions/632742/how-can-i-avoid-running-activerecord-callbacks) – phoet Oct 18 '13 at 12:23
  • 1
    @phoet i've tried with that answer but i think doesn't work in rails 4 – Yassine S. Oct 18 '13 at 12:25

4 Answers4

20

skip_callback is a complicated and not granular option.

I prefer to use an attr_accessor:

attr_accessor :skip_my_method, :skip_my_method_2
after_save{ my_method unless skip_my_method }
after_save{ my_method_2 unless skip_my_method_2 }

That way you can be declarative when skipping a callback:

model.create skip_my_method: true # skips my_method
model.create skip_my_method_2: true # skips my_method_2
sites
  • 21,417
  • 17
  • 87
  • 146
5

ActiveSupport::Callbacks::ClassMethods#skip_callback is not threadsafe, it will remove callback-methods for time till it is being executed and hence and another thread at same time cannot get the callback-methods for execution.

Look at the informative post by Allerin - SAVE AN OBJECT SKIPPING CALLBACKS IN RAILS APPLICATION

Allerin
  • 1,108
  • 10
  • 7
4

You can try skipping callback with skip_callback

http://www.rubydoc.info/docs/rails/4.0.0/ActiveSupport/Callbacks/ClassMethods:skip_callback

akusy
  • 41
  • 3
  • 1
    That's works! Here the useful post about this method: http://manuel.manuelles.nl/blog/2012/01/12/disable-rails-before-slash-after-callback/ – Stepan Zakharov Jan 13 '15 at 15:51
2

You can use update_columns See this http://edgeguides.rubyonrails.org/active_record_callbacks.html#skipping-callbacks

Is there any specific condition like when you don't have endtime then only you need to set end time if that the you can do

def set_endtime 
   if endtime.nil? 
     self.endtime=self.starttime+self.auctiontimer 
   end 
end 

OR

before_update :set_endtime if: Proc.new { |obj| obj.endtime.nil? }
userxyz
  • 1,100
  • 8
  • 14