Rails 4:跳过回调 [英] Rails 4: Skip callback

查看:499
本文介绍了Rails 4:跳过回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程式中有竞价和竞价物件,当有人按下 BID按钮时,系统会呼叫建立出价的 BID CREATE 控制器拍卖物品上的其他部分:



BIDS控制器 - > CREATE

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

拍卖模型

  before_update:set_endtime 

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

所以问题是:如何C只跳过before callback,在这个特定的@ auction.save

解决方案

skip_callback 是一个复杂而不是粒度的选项。



我更喜欢使用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}



这样你可以在跳过回调时声明:

  model.create skip_my_method:true#skips my_method 
model.create skip_my_method_2:true#skips my_method_2


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

解决方案

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

这篇关于Rails 4:跳过回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆