Ruby-on-rails Rails 4:跳过回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19449019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:53:23  来源:igfitidea点击:

Rails 4: Skip callback

ruby-on-railsrubycallback

提问by Crazy Barney

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

我的应用程序中有一个拍卖和一个出价对象,当有人按下BID 按钮时,它会调用创建出价的BID CREATE控制器,然后对拍卖对象执行一些其他操作:

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

所以问题是:在这个特定的@auction.save 中,C 如何仅跳过“回调之前”

回答by sites

skip_callbackis 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

回答by Allerin

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 的信息性帖子 -在 RAILS 应用程序中保存对象跳过回调

回答by userxyz

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#skiping-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? }