2011-12-16 79 views
0

想象一個簡單的I-O-U應用程序,其中有User模型和Transaction模型。將多個列映射到同一張表

User表有以下幾列:

  • ID

Transaction表有以下幾列:

  • lender_id(外鍵User.id
  • borrower_id(外鍵User.id
  • 日期

用戶只能借出或借入到存在於User表另一個用戶。

一個例子是:

User: 

id | name 
------------- 
    1 | name A 
    2 | name B 
    3 | name C 

Transaction: 

lender_id | borrower_id | date 
---------------------------------- 
    1  |  2  | date1 
    1  |  3  | date2 
    3  |  2  | date3 

我將如何實現模型類的關聯?

+0

你需要[belongs_to](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to)嗎? – aishwarya 2011-12-16 06:40:40

回答

2

在交易:

belongs_to :lender, :class_name => "User" 
belongs_to :borrower, :class_name => "User" 

在用戶:

has_many :loans, :class_name => "Transaction", :foreign_key => "lender_id" 
has_many :debts, :class_name => "Transaction", :foreign_key => "borrower_id" 

這給了你:

u = User.first 
u.loans # [transaction, transaction, ...] 
u.debts # [transaction, transaction, ...] 

而且

t = Transaction.first 
t.lender # User 
t.borrower # User 

希望這有助於!

相關問題