[英]Rails 4 - Using Transactions along with Begin rescue block
我有一段代碼用於執行從控制器調用觸發的操作,我正在使用Rails Transaction和begin / rescue結束塊來使以下代碼執行更加健壯,如下所示:
重新導向
###in my controller def verify @request=Request.includes(:user).find(params[:id]) @request.transaction do begin if @request.accepted? ##this method will call 3 more methods in the request model @request.send_email_and_sms flash[:success] = "Request is moved to another state" else flash[:error] = "Request was not accepted and couldn't be moved to another state" end rescue flash[:alert] = "There was some internal error.Kindly debug" ensure @request.reload Rails.logger.info "================Making GO AHEAD TOKEN FALSE AND DEACTIVATE VENUE====================#{@request.attributes}===========" redirect_to request_hall_path(@request.user) end end end
`
這是確保每段代碼都將執行的正確方法嗎,否則它將通過flash.alert消息跳入救援。
還有什么其他方法可以使我的代碼/邏輯更傻瓜和更可靠?
提前致謝。
我認為您不需要在這里進行交易。 當您有“全部或沒有”要求時,您將希望使用事務。 例如銷售產品和創建發票之類的東西。 您不會希望其中一個步驟導致序列失敗,並且數據庫狀態不一致(即:不從庫存數量中扣除,而是增加銷售額)。
另外,就您所知(從上面的評論中得知),發送電子郵件和短信應通過異步作業完成,以免阻塞當前線程。
無論如何,我認為這樣會很好:
def verify
@request = Request.includes(:user).find(params[:id])
if @request && @request.accepted?
##this method will call 3 more methods in the request model
@request.send_email_and_sms # send async
flash[:success] = "Request is moved to another state"
else
flash[:error] = "Request was not accepted and couldn't be moved to another state"
end
redirect_to request_hall_path(@request.user)
end
如果您的#send_email_and_sms有任何數據庫寫入,那么您可能可以使用作業掛鈎(例如:delay_job回調)進行寫入,因此您可以確定該作業已成功完成。 因此,請注冊一個回調,以便在成功發送電子郵件和短信后,您可以像request.update(email_sent: true)
希望有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.