2012-06-15 39 views
8

我目前有兩種不同的型號:UserProjectUser模型有三種類型的用戶 - 所有者,承包商和客戶。我想將多個承包商分配給一個項目。我用has_many :through協會試圖這樣,就像這樣:Rails has_many:通過關聯表中的不同列名稱

Class User 
    has_many :assignments 
    has_many :projects, :through => :assignments 

Class Project 
    has_many :assignments 
    has_many :contractors, :through => :assignments 

Class Assignment 
    belongs_to :user 
    belongs_to :project 

我的問題是在assignments表使用contractor_id代替user_id

在我的assignments表中,我目前有contractor_idproject_id列。如果我使用user_id來代替所有東西,似乎都可以工作,但這會在我的觀點中導致事情變得非常混亂。

我該如何做到這一點?

回答

14

您應該使用:foreign_key選項Assignment,如:

class Assignment 
    belongs_to :user, :foreign_key => :contractor_id 
    belongs_to :project 
+0

這絕對作品的一種方式,現在我只需要獲得用戶模型識別'contractor_id',而不是'user_id'當我調用'@ user.projects' –

+2

瞭解它。需要的用戶模型:foreign_key =>:has_many:assignments上的contractor_id –

相關問題