Ruby on Rails -多对一类型关联



我正在尝试创建某种多对一关联。基本前提是一个资金/交易流系统,用于跟踪用户两个账户之间的资金(可能在钱包和支票账户之间)。

我有一个Transaction模型,它存储了基本信息——从哪个账户借,从哪个账户贷,金额是多少。

我还有一个帐户模型,用户可以创建多个帐户模型(可能一个用于钱包,一个用于信用卡,一个用于支票帐户,等等)。

我认为我遇到的问题是,我的事务模型引用帐户模型两次,一次用于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

使用这个模型实现,我可以获得事务。信用卡和交易,借记都是正确的,但当我尝试做一些像账户之类的事情时。credit_transactions,我得到这个错误:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: transactions。account_id:选择"accounts"。*从"accounts"内部连接"transactions"到"accounts"。id = "transactions".debit_id WHERE (("transactions")。Account_id = 3))

老实说,我有点卡住了,不知道下一步该去哪里,所以任何帮助都会很感激。谢谢!

[edit: updated model code]

听起来您的交易有一个贷方账户和一个借方账户吗?
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

如果这不起作用,你能给一点关于你的模型之间的关系应该工作的更多信息吗?

抱歉耽搁了,但我终于想明白了。这是我的代码

    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'

感谢所有帮助我的人!

最新更新