0

我試圖創建某種多對一的關聯。基本前提是用於跟蹤用戶兩個賬戶(可能在錢包和支票賬戶之間)之間的資金的貨幣/交易流系統。Ruby on Rails - 多對一類型關聯

我有一個交易模型,它存儲了基本信息 - 從哪個帳戶借記,要記入哪個帳戶,金額是多少。

我也有一個賬戶模式,用戶可以創建多個賬戶模式(也許一個用於電子錢包,一個用於信用卡,一個用於支票賬戶等)。

我想我遇到的問題是我的交易模型引用帳戶模型兩次,一次爲credit_id,一次爲debit_id。

我想弄清楚我需要的關聯,我想我需要一個多對一(很多交易,一個帳戶)。我不認爲我需要一個連接表,但我不完全確定。

這是我的基本模型代碼,我真的不知道該從哪裏出發。

class Transaction < ActiveRecord::Base 
    attr_accessible :amount, :description, :credit_id, :debit_id 

    belongs_to :user 

    belongs_to :debit, :class_name => "Account" 
    belongs_to :credit, :class_name => "Account" 


end 

然後爲Account模型:

class Account < ActiveRecord::Base 
    attr_accessible :name, :credit_transactions, :debit_transactions 

    belongs_to :user 

    has_many :transactions 
    has_many :credit_transactions, :through => :transactions, :source => :credit 
    has_many :debit_transactions, :through => :transactions, :source => :debit 
end 

在這種模式的實現,我可以正確得到transaction.credit和transaction.debit,但是當我嘗試做這樣account.credit_transactions東西,我得到這個錯誤:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: transactions.account_id: SELECT "accounts".* FROM "accounts" INNER JOIN "transactions" ON "accounts".id = "transactions".debit_id WHERE (("transactions".account_id = 3))

我說實話有點卡住關於下一步去哪裏,所以任何幫助,將不勝感激。謝謝!

[編輯:更新的模型代碼]

回答

0

對不起,延遲了,但最後弄明白了。這裏是我的代碼

class Transaction < ActiveRecord::Base 
     attr_accessible :amount, :description, :long_description, :credited_id, :debitted_id, :custom_credit, :custom_debit 

     belongs_to :user 

     belongs_to :debitted, :class_name => "Account" 
     belongs_to :credited, :class_name => "Account" 

和帳戶

class Account < ActiveRecord::Base 
     attr_accessible :name, :debit_shorthand, :credit_shorthand, :credit_transactions, :debit_transactions 

     belongs_to :user 

     has_many :credit_transactions, :class_name => "Transaction", :foreign_key => 'credited_id' 
     has_many :debit_transactions, :class_name => "Transaction", :foreign_key => 'debitted_id' 

感謝所有誰幫助!

0

通過它您的交易都有一個信用賬戶,一個賬戶借方的聲音?

class Transaction < ActiveRecord::Base 

    has_one :credit_account, :class_name => "Account", :foreign_key => "credit_account_id" 
    has_one :debit_account, :class_name => "Account", :foreign_key => "debit_account_id" 

end 

如果這樣做不行,你可以就如何您的模型應該工作之間的關係多一點信息?

+0

很少有人會使用這樣的一對一關聯,雖然......也許說一個交易屬於一個信用賬戶並且屬於一個DebitAccount – bodacious

+0

感謝博多!我實際上改變了我的代碼,並採取了你的評論性建議。當我嘗試做一個transaction.credit和transaction.debit時,我可以得到正確的Account模型。但是,我不能做相反的事情;例如account.credit_transactions或account.debit_transactions。我得到錯誤「ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:沒有這樣的列:transactions.account_id:SELECT」accounts「。* FROM」accounts「INNER JOIN」transactions「ON」accounts「.id =」transactions「.debit_id WHERE((「transactions」.account_id = 3))「;任何幫助?哈哈 – Josiah

+0

它只是不工作,我認爲。使用has_one,交易的外鍵將在賬戶上,但賬戶可以有許多交易。 – Robin