Forum: Ruby on Rails belongs_to with has_and_belongs_to_many

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
84962fcce3fbde5aef15001d60e242ae?d=identicon&s=25 Michael Glaesemann (Guest)
on 2006-01-16 08:28
(Received via mailing list)
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'

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

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 Glaesemann
grzm myrealbox com

This topic is locked and can not be replied to.