2013-02-22 61 views
1

這裏是我想要做的事:Rails的模型加入的has_many

class Cashflow < ActiveRecord::Base 
    belongs_to from_account, :class_name => 'Account' 
    belongs_to to_account, :class_name => 'Account' 
end 

class Account < ActiveRecord::Base 
    has_many :cashflows 
end 

其中Account::cashflows顯然是所有cashflows的列表,要麼存儲在from_accountto_accountaccount_id

我很困惑。處理這種情況的正確方法是什麼?這是多麼糟糕的設計?設計這種關係的正確方法是什麼?

回答

2

我認爲你有正確的結構,因爲在特定的交易/現金流中只能涉及兩個賬戶。如果您使用多對多關聯,則需要處理驗證,而不涉及多於或少於2個帳戶。對於當前的結構,你可以改變你的moidel協會是:

class Cashflow < ActiveRecord::Base 
    belongs_to from_account, :class_name => 'Account', :foreign_key => :from_account 
    belongs_to to_account, :class_name => 'Account', :foreign_key => :to_account 
end 

class Account < ActiveRecord::Base 
    has_many :debits, :class_name => 'Cashflow', :foreign_key => :from_account 
    has_many :credits, :class_name => 'Cashflow', :foreign_key => :to_account 

    def cashflows 
    transactions = [] 
    transactions << self.debits 
    transactions << self.credits 
    transactions.flatten! 

    ## or may be the following commented way 
    # Cashflow.where('from_account = ? OR to_account = ?', self.id, self.id) 
    end 
end 

這樣你就可以跟蹤/扣款金額在特定賬戶貸記並同時獲得參與特定交易/現金流賬戶。

+0

聽起來沒錯。現在,我有大量需要做'account.cashflows'的對象。我想我可以使用這個範圍。你會建議什麼? – muichkine 2013-02-22 11:41:31

+0

另外一個問題是:您如何獲得SIGNED現金流清單。像'account.cashflows'現金流有給定帳戶的有符號值?!這是一個棘手的問題。 :/ – muichkine 2013-02-22 11:43:07

+0

如果您創建了一個關聯,那麼它會在'cashflows'表中查找'account_id'。如果你創建一個範圍,那麼你就不能在模型實例中使用它,所以你需要創建一個'cashflows'方法。你認爲SIGNED現金流量是什麼意思? – 2013-02-22 11:56:40

1

我認爲你應該使用有屬於一對多的關聯在這裏:

class Account < ActiveRecord::Base 
    has_and_belongs_to_many :incoming_cashflows, :class_name => 'Cashflow', :join_table => :incoming_cashflows_accounts 
    has_and_belongs_to_many :outcoming_cashflows, :class_name => 'Cashflow', :join_table => :outcoming_cashflows_accounts 
end 

class Cashflow < ActiveRecord::Base 
    has_and_belongs_to_many :from_accounts, :class_name => 'Account', :join_table => :incoming_cashflows_accounts 
    has_and_belongs_to_many :to_accounts, :class_name => 'Account', :join_table => :outcoming_cashflows_accounts 
end 

你也將需要一些驗證碼允許只有一個帳戶添加到現金流。在我心中的頂部

1)您的類(表)cashflows

+0

這就是我最初想到的。現在解決方案的麻煩是你無法區分現金流的方向。現金流量具有:金額字段,其中攜帶的值對from_account有負面影響,對to_account有正面影響。任何想法? – muichkine 2013-02-22 11:17:31

+0

我認爲你可以很容易地解決這個問題 - 添加get_direction方法,它會根據from_accounts和:to_accounts項數返回結果。在傳入現金流to_accounts.count將始終爲0,在輸出 - from_accounts.count將始終爲0. – 2013-02-22 11:39:20

2

建議應該有兩列from_account和to_account。

2)from_accountto_account應具有帳戶有關

3的ID)cashflowsbelongs_to :account

4)accounthas_many :cashflows。理想情況下,它應該是cash_flows

這些應該是很好的起點。他們不符合你的要求嗎?

+0

是的先生!除4外,我不認爲命名約定會影響到這裏。 – muichkine 2013-02-22 11:15:52

+1

@Arindam模型類是'Cashflow'而不是'CashFlow',因此關聯名稱是正確的。 – 2013-02-22 11:24:33

+0

對。錯過了。謝謝 – Arindam 2013-02-22 12:05:17

相關問題