0

我有以下:has_many :through關係。有很多通過與不同的外鍵

協會

class Profile < ActiveRecord::Base 
    has_many :teams 
    has_many :projects, :class_name => "Project", :through => :teams 
    has_many :leads, :class_name => "Projects" 

class Project < ActiveRecord::Base 
    has_many :teams 
    has_many :developers, :class_name => "Profile", :through => :teams 
    belongs_to :lead, :class_name => "Profile", :foreign_key => "developer_lead" 

class Team < ActiveRecord::Base 
    belongs_to :developer, :class_name => "Profile" 
    belongs_to :project 

當我試圖得到一個檔案項目的關係,不使用隊中的表右鍵。

滑軌Ç

1.9.3p194:001> Profile.first.projects

資料負荷(0.2ms的)選擇 「配置文件」 * FROM 「配置文件」 LIMIT 1
項目。 Load(0.2ms)SELECT「projects」。* FROM「projects」INNER JOIN「teams」ON「projects」。「id」= 「teams」。「project_id」WHERE 「teams」。「profile_id」= 1

應該使用"teams"."developer_id" = 1

我試圖在配置文件和項目模型都使用:foreign_key => "developer_id",但似乎沒有任何工作。

我覺得我對模型所做的更改沒有產生任何影響,但每次更改後我都重新啓動了rails控制檯。

架構

create_table "profiles", :force => true do |t| 
    t.datetime "created_at",   :null => false 
    t.datetime "updated_at",   :null => false 
end 

create_table "projects", :force => true do |t| 
    t.integer "developer_lead" 
    t.datetime "created_at",  :null => false 
    t.datetime "updated_at",  :null => false 
end 

create_table "teams", :id => false, :force => true do |t| 
    t.integer "developer_id" 
    t.integer "project_id" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
end 
+0

':foreign_key =>「developer_id」'屬於'has_many:teams'。 SQL產生了什麼? – cdesrosiers

+0

啊,太棒了,工作。 SQL:'SELECT「projects * FROM」projects「INNER JOIN」teams「ON」projects「。」id「=」teams「。」project_id「WHERE」teams「。」developer_id「= 1'。如果你把答案扔在答案中,我會接受它。 – travis

回答

1

:foreign_key => "developer_id"屬於與has_many :teams

此外,如果您堅持使用rails約定並使用「_id」結束所有foreign_key名稱(如在「developer_lead_id」中),則會使代碼更加清晰。