[英]Rails 4: Skip callback
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: 我的应用程序中有拍卖和出价对象,当有人按下BID BUTTON然后调用创建出价的BID CREATE控制器,然后在拍卖对象上做一些其他事情:
BIDS CONTROLLER -> CREATE BIDS控制器 - >创建
@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 所以问题是:在这个特定的@ auction.save中,C如何才能跳过“回调前”
skip_callback
is a complicated and not granular option. skip_callback
是一个复杂而非粒度的选项。
I prefer to use an attr_accessor: 我更喜欢使用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
You can try skipping callback with skip_callback 您可以尝试使用skip_callback跳过回调
http://www.rubydoc.info/docs/rails/4.0.0/ActiveSupport/Callbacks/ClassMethods:skip_callback http://www.rubydoc.info/docs/rails/4.0.0/ActiveSupport/Callbacks/ClassMethods:skip_callback
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. ActiveSupport :: Callbacks :: ClassMethods #skip_callback不是线程安全的,它将删除回调方法的时间直到它被执行,因此另一个线程同时无法获得回调方法来执行。
Look at the informative post by Allerin - SAVE AN OBJECT SKIPPING CALLBACKS IN RAILS APPLICATION 看看Allerin提供的信息性帖子 - 在轨道应用中保存一个对象跳过的回调
You can use update_columns See this http://edgeguides.rubyonrails.org/active_record_callbacks.html#skipping-callbacks 您可以使用update_columns请参阅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? }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.