3

我有這2種型號如下保證協會後主要模式已被保存並創建軌道4

class Application < ActiveRecord::Base 
    has_many :commitments, class_name: "Commitment", \ 
    :source => :application, dependent: :destroy 
    accepts_nested_attributes_for :commitments 

    after_create: update_case_code 

end 

class Commitment < ActiveRecord::Base 
    belongs_to :application 
    after_create: send_notification 

    def send_notification 
    ap self.application.case_code 
    end 
end 

class ApplicationsController < ApplicationController 
    def create 
    @application = Application.new(params) 
    @application.save 
    end 
end 

在我application_controller每當我創建一個新的應用程序紀錄,新紀錄,也創造了在承諾中,它試圖從應用程序記錄中獲取case_code,但應用程序模型的after_create方法尚未執行。

有沒有什麼辦法可以優化這段代碼,使其正常工作?

+0

'它試圖從應用程序記錄中獲取case_code,但應用程序模型的after_create方法尚未執行'這是什麼意思。它調用'send_notification'的原因是因爲'after_create'回調被調用。 – Abhinay

+0

應用程序模型中的after_create僅在承諾模型中的after_create之後執行。我希望它是相反的方式 –

+0

正如你已經正確地提到的那樣,並且如果我已經正確地理解了它,那麼在創建'應用程序'模型中的記錄之前,它會繼續在'承諾'模型中創建記錄。因爲它取決於它 – Abhinay

回答

1

可能有。也許你也可以在應用程序模型上使用另一個回調函數,這種回調函數有很多。見Active Record Callbacks

然而這正是情況下,其他人叫rails callback hell

這裏最好的做法是隻創建一個表單對象,這在您需要的順序創建數據,並刪除回調

class ApplicationCommitmentForm 
    include ActiveModel::Model 


    attr_accessor ... 

    def submit 
    a = Application.create .. 
    a.update_case_code 
    a.commitments.create ... 
    end 


end 

ActiveModel Form Objects

順便說一句,你也可以換提交代碼到一個交易,確保無論是創建或在任何錯誤nothi的情況下,所有記錄一點都不。