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的?