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

当我尝试获取 Profiles 项目时,该关系未使用 team 表中的正确键。

导轨 C

1.9.3p194:001 > Profile.first.projects

配置文件加载(0.2ms)选择“profiles”。* FROM“profiles”限制1
项目加载(0.2ms)选择“projects”。*从“projects”INNER JOIN“teams”ON“projects”。“id”=“teams "."project_id" WHERE "teams"."profile_id" = 1

它应该使用"teams"."developer_id" = 1

我已经尝试:foreign_key => "developer_id"在 Profile 和 Project 模型中使用 a ,但似乎没有任何效果。

我觉得我对模型所做的更改没有产生任何影响,尽管每次更改后我都在重新启动 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 
4

1 回答 1

1

:foreign_key => "developer_id"属于has_many :teams.

此外,如果您遵守 Rails 约定并以“_id”结尾所有外键名称,如“developer_lead_id”,它会使您的代码更清晰。

于 2012-09-24T20:41:33.897 回答