2009-09-15 52 views
3

这是一个单独的问题,但它关系到一个较早的问题:Three Column Join in Rails with Active Scaffold。综上所述:Rails的自动查找两列连接表,但它并不适用于三列连接表做同样的。我试着在前面的问题的建议,但它归结为:别名表名,以方便3列连接表(MySQL或PostgreSQL)

如果你有模型项目,员工,角色和每个具有其他两个的habtm关系,轨将分别做各的关系,但不是整体。

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 

重复项目,角色如下

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 

我的问题是这样的,因为轨道寻找employees_projects, projects_roles,并employees_roles但不employees_projects_roles是有没有办法别名这些名称与实际表名和仍然允许数据库中的CRUD功能(MySQL或PostgreSQL)?

[编辑] 糟糕。我必须停止回答和提问我已经受够了咖啡公开之前。将注释掉的部分从hmt更改为habtm。包括注释掉部分代码以反映我尝试过的各种选项。

回答

6

我假设你有这样的事情您的加盟模式一起:

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 

如果是这样你,只需要指定与您的habtm使用join表的名称。

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 
+0

是的,连接表存在,但没有我不知道:join_table属性!即使在过去的几周内使用Google搜索功能。谢谢你的帮助! – 2009-09-15 18:55:19