0

I have the following :has_many :through relation.

Associations

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

When I try to get a Profiles projects the relationship doesn't use the right key in the teams table.

Rails C

1.9.3p194 :001 > Profile.first.projects

Profile Load (0.2ms) SELECT "profiles".* FROM "profiles" LIMIT 1
Project Load (0.2ms) SELECT "projects".* FROM "projects" INNER JOIN "teams" ON "projects"."id" = "teams"."project_id" WHERE "teams"."profile_id" = 1

It should be using "teams"."developer_id" = 1

I've tried using a :foreign_key => "developer_id" in both the Profile and Project models, but nothing seems to work.

I feel like the changes to the models I've been making aren't taking any effects, after each change I've been restarting the rails console though.

Schema

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 
travis
  • 8,055
  • 1
  • 17
  • 19
  • `:foreign_key => "developer_id"` belongs with `has_many :teams`. What SQL does that generate? – cdesrosiers Sep 24 '12 at 20:19
  • Ah great, that worked. SQL: `SELECT "projects".* FROM "projects" INNER JOIN "teams" ON "projects"."id" = "teams"."project_id" WHERE "teams"."developer_id" = 1`. If you throw that up in an answer I'll accept it. – travis Sep 24 '12 at 20:25

1 Answers1

1

:foreign_key => "developer_id" belongs with has_many :teams.

Also, it makes your code clearer if you stick to rails conventions and end all foreign_key names with "_id", as in "developer_lead_id".

cdesrosiers
  • 8,862
  • 2
  • 28
  • 33