I'm trying to create some sort of many-to-one association. The basic premise is a money/transaction flow system to keep track of money between a user's two accounts (perhaps between a wallet and a checking account).
I have a Transaction model, which stores the basic information - what account to debit from, what account to credit to, what the amount is.
I also have an Account model, which the user can create multiple ones of (maybe one for Wallet, one for Credit Card, one for Checkings Account, etc).
The problem I think I'm running into is that my Transaction model references the Account model twice, once for a credit_id and once for a debit_id.
I'm trying to figure out the association I need, and I think I need a many-to-one (many transactions, one account). I don't think I need a join table, but I'm not entirely sure.
Here's my basic model code, I'm really not sure where to go from here.
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
And then for Account model:
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
With this model implementation, I can get transaction.credit and transaction.debit correctly, but when I try do something like account.credit_transactions, I get this error:
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))
I'm honestly kinda stuck about where to go next, so any help would be appreciated. Thanks!
[edit: updated model codes]
Sorry for the delay, but finally figured it out. Here's my code
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"
and for 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'
Thanks all who helped!