我已經構建了一個幫助用戶監視各種金融產品的應用程序。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
。
在此先感謝!