2012-08-06 90 views
1

我正在編寫一個具有用戶模型的應用程序,並且此模型中的用戶可以是兩種不同的用戶類型。Rails 3多個外鍵

user.rb

class User < ActiveRecord::Base 
    has_many  :transactions 
    has_many  :transaction_details, :through => :transactions 
    has_many  :renters, :class_name => "Transactions" 
end 

transaction.rb

class Transaction < ActiveRecord::Base 
    has_many  :transaction_details 
    belongs_to  :user 
    belongs_to  :renter, :class_name => "User" 
end 

transaction_detail.rb

class TransactionDetail < ActiveRecord::Base 
    belongs_to :transaction 
    belongs_to :inventory 

    scope :all_open, where("transaction_details.checked_in_at is null") 
    scope :all_closed, where("transaction_details.checked_in_at is not null") 
end 

基本上是一個用戶可能是一個承租人,或檢查項目出來的人。一旦我有交易,我可以打電話:

@transaction.renter.first_name # receive the first name of the renter from the renter table 
@transaction.user.first_name  # receive the first name of user who performed the transaction 

這是完美的,我工作正如我所說的。對於我的生活,我無法弄清楚如何獲得範圍合作,通過用戶調用時:

# trying to perform the scrope "all_open", limted to the current user record, but I cant get it to use the 
# renter_id column instead of the user_id column 
u.transaction_details.all_open 

是這可能有一個斯克羅普查找由第二forien_key而不是user_ID的?

回答

0

簡短的回答 - 是的。這是非常可能的。

您需要提及反向關聯定義中使用的foriegn鍵。

在users.rb的:

has_many :rents, :class_name => "Transactions", :foreign_key => "renter_id" 

這將允許你寫:

User.find(5).rents # array of transactions where user was renter 

如果你想直接調用transaction_details,然後再一次你需要指定另一個關聯user.rb:

has_many :rent_transaction_details, :through => :rents, :source => "TranactionDetail" 

哪個可以讓你打電話:

User.find(5).rent_transaction_details.all_open