views:

719

answers:

1

This is a separate question, but it is related to an earlier question: Three Column Join in Rails with Active Scaffold. To sum up: Rails automatically looks for a two column join table, but it doesn't do the same for a three column join table. I've tried the suggestions in the previous question, but it comes down to this:

If you have the models Project, Employee, Role and each has a habtm relationship to the other two, rails will do each relationship separately but not as a whole.

class Employee < ActiveRecord::Base
    #has_many        :employees_projects_roles
    #has_many        :roles,     :through => :employees_projects_roles
    #has_many        :projects,  :through => :employees_projects_roles
     has_and_belongs_to_many :roles
     has_and_belongs_to_many :projects
end

repeated for Project, Role follows

class Role < ActiveRecord::Base
    #has_many :employees, :through => :employees_projects_roles
    #has_many :projects,  :through => :employees_projects_roles
    has_and_belongs_to_many :employees
    has_and_belongs_to_many :projects
end

My question is this, since rails looks for employees_projects, projects_roles, and employees_roles but not employees_projects_roles is there a way to alias those names to the real table name and still allow CRUD functionality in the database (MySQL or PostgreSQL)?

[Edit] Whoops. I have got to stop answering and questioning publicly before I've had enough coffee. Changed the commented out portion from hmt to habtm. Included commented out portion of code to reflect the various options I've tried.

+2  A: 

I'm assuming that you have something like this joining your models together:

  def self.up
    create_table :my_join_table, :id => false do |t|
      t.integer :employee_id
      t.integer :role_id
      t.integer :project_id
      t.timestamps
    end
  end

If so you, simply need to specify the name of the join table to use with your habtm.

class Employee < ActiveRecord::Base
  has_and_belongs_to_many :roles, :join_table => "my_join_table"
  has_and_belongs_to_many :projects, :join_table => "my_join_table"
end

class Project < ActiveRecord::Base
  has_and_belongs_to_many :roles, :join_table => "my_join_table"
  has_and_belongs_to_many :employees, :join_table => "my_join_table"
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :employees, :join_table => "my_join_table"
  has_and_belongs_to_many :projects, :join_table => "my_join_table"
end
jdl
Yes, the join table existed, but no I had not known about the :join_table attribute! Even with mucho Googling the past couple weeks. Thanks for your help!
Elizabeth Buckwalter