Rails 4: Skip callback
Solution 1
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
Solution 2
You can try skipping callback with skip_callback
http://www.rubydoc.info/docs/rails/4.0.0/ActiveSupport/Callbacks/ClassMethods:skip_callback
Solution 3
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
Solution 4
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? }
Yassine S.
Updated on July 29, 2022Comments
-
Yassine S. almost 2 years
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
-
Yassine S. over 10 yearsThis is a way but skips validations, i want just to skip callbacks :)
-
userxyz over 10 yearsIs 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
-
userxyz over 10 yearsUpdate my answer with example
-
Stepan Zakharov over 9 yearsThat's works! Here the useful post about this method: manuel.manuelles.nl/blog/2012/01/12/…
-
jlstr almost 9 yearsThis is the correct answer for save/update callbacks!
-
Dex over 7 yearsI've used this as well. Other methods could run into threading issues.
-
Swaps about 7 yearsconsidering your approach I have tried slightly different solution which works with
rails 5
. Please check this answer stackoverflow.com/a/42945367/4675524 -
Toby 1 Kenobi almost 7 yearsin what way is
skip_callback
not granular?