我有以下: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
当我尝试获取个人资料项目时,该关系不会在团队表中使用正确的密钥。
Rails C
1.9.3p194:001&gt; Profile.first.projects
Profile Load(0.2ms)SELECT“profiles”。* FROM“profiles”LIMIT 1
项目负载(0.2ms)SELECT“projects”。* FROM“projects”INNER JOIN“teams”ON“projects”。“id”= “团队”。“project_id”在哪里“团队”。“profile_id”= 1
它应该使用"teams"."developer_id" = 1
我尝试在Profile和Project模型中使用: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 :(得分:1)
:foreign_key => "developer_id"
属于has_many :teams
。
此外,如果您坚持使用rails约定并使用“_id”结束所有foreign_key名称,它会使您的代码更清晰,如“developer_lead_id”。