# Belongs\_to with has\_and\_belongs\_to\_many

**URL:** <https://www.ruby-forum.com/t/belongs-to-with-has-and-belongs-to-many/52547>\
**Category:** Rails\
**Created:** [January 16, 2006, 8:28am UTC](https://www.ruby-forum.com/t/belongs-to-with-has-and-belongs-to-many/52547 "2006-01-16T08:28:51Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mgreenly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85f322/32.png) [@mgreenly](https://www.ruby-forum.com/u/mgreenly)\
**Post date:** [January 16, 2006, 8:28am UTC](https://www.ruby-forum.com/t/belongs-to-with-has-and-belongs-to-many/52547/1 "2006-01-16T08:28:51Z")

</div>

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](http://www.loudthinking.com/arc/000229.html)
