2012-07-11 18 views
1

我已經構建了一個幫助用戶監視各種金融產品的應用程序。Get Rails保存使用自定義setter方法構建的子記錄(而不是accept_nested_attributes_for)

在大約6-10個不同的模型,每個跟蹤不同類型的金融產品(信用卡,儲蓄賬戶等),我以前有一個balance列(用於存儲用戶的當前餘額)和一個repayments列隨時間存儲用戶對賬戶的平均貢獻。

我現在想存儲歷史餘額更新,我認爲最好的方法是創建一個單獨的balance模型,可以通過多態關係模型belongs_to所有這些模型。那麼每個賬戶在歷史的不同點可以有has_many餘額,我可以很容易地將用戶最近的balance拔出。

我喜歡這樣的解決方案,但有一堆定製用戶表單創建/與balance領域,repayments領域,以及將抽象到一個Balance模式中的一些其他領域的編輯帳戶。我不想花費數小時去瀏覽這些表單並更改字段以適應新的嵌套結構。相反,我創建了一堆的輔助方法。因而沒有我的看法不同需要與我的模型進行互動,像這樣將處理所有的後端邏輯:

#creditcard_account.rb 
    has_many :balances, :as => :balanceable, :dependent => :destroy 

    def latest_balance 
    balances.order("created_at DESC").first 
    end 

    def new_balance 
    @new_balance ||= balances.build 
    end 

    def balance=(input_balance) 
    new_balance.amount = input_balance 
    end 

    def balance 
    new_balance.balance || (latest_balance? ? self.latest_balance.amount : nil) 
    end 

    def repayment_amount=(input_repayment_amount) 
    new_balance.contribution_amount = input_repayment_amount 
    end 

    def repayment_amount 
    new_balance.contribution_amount || (latest_balance ? latest_balance.contribution_amount : nil) 
    end 

    def repayment_period=(input_repayment_period) 
    new_balance.contribution_period = input_repayment_period 
    end 

    def repayment_period 
    new_balance.contribution_period || (latest_balance ? latest_balance.contribution_period : nil) 
    end 

問題: 此作品精細,EXCEPT @new_balance沒有得到保存,如果相關creditcard_account沒有實際屬性改變。也就是說,Rails Dirty Model方法並不知道我已經創建了一個子項,並且父項需要被保存。

如何告訴Rails我爲這個模型創建了一個子模型,並且模型(和它的子模塊)需要保存?

如果是很重要的,有問題的所有形式居然有creditcard_account如在form_for :user嵌套fields_for

在此先感謝!

回答

0

我最終迫使家長通過設定父Time.now的的updated_at屬性保存,這樣父被標記爲changed?,因此被保存(及其子女):

def balance=(input_balance) 
    new_balance.amount = input_balance 
    self.updated_at = Time.now 
    end 

    def repayment_amount=(input_repayment_amount) 
    new_balance.contribution_amount = input_repayment_amount 
    self.updated_at = Time.now 
    end 

    def repayment_period=(input_repayment_period) 
    new_balance.contribution_period = input_repayment_period 
    self.updated_at = Time.now 
    end 

對於任何嘗試類似的人來說,請注意,我的方法引發了其他問題:例如,對這些虛擬屬性的驗證幾乎中斷。

相關問題