Belongs_to with has_and_belongs_to_many


#1

I’m having a problem with belongs_to and has_and_belongs_to_many.
Here’s a brief summary of the models involved:

class Member < ActiveRecord::Base
set_primary_key ‘member_id’
has_and_belongs_to_many :projects, :join_table => ‘projects__members’
has_many :projects, :foreign_key => ‘created_by’
end

class Project < ActiveRecord::Base
set_primary_key ‘project_id’
belongs_to :created_by, :class_name => ‘Member’, :foreign_key =>
‘created_by’
has_and_belongs_to_many :members, :join_table => ‘projects__members’
end

And the DDL:

create table members (
member_id serial primary key
, email_address text not null unique
, is_active boolean not null default true
, is_admin boolean not null default false
, can_produce boolean not null default false
);

create table projects (
project_id serial primary key
, project_name text not null unique
, created_by integer not null
references members (member_id)
);

create table projects__members (
project_id integer not null
references projects(project_id)
, member_id integer not null
references members(member_id)
, is_producer boolean not null default false
, is_active boolean not null default true
, unique (project_id, member_id)
);

From looking at the SQL that gets called, a statement like
@member.projects.find(:all) appears to be doing something like

select projects.*
from members
join projects on (member_id = created_by).

Most of the time, I’d like it to make the join through the
projects__members table. However, that’s besides the point. How can I
specify how the join is made? Is there something obviously wrong with
my schema? I’ve been looking through AWDwR, googling, and searching
my mailing list archives, but I haven’t found a solution. (I’m
surprised I haven’t found anything and think I must have missed
something obvious, because I don’t think this is that obscure.)

Thanks for any advice and suggestions.

Michael G.
grzm myrealbox com

1