别名表名称便于3列连接表(MySQL或PostgreSQL)

Eli*_*ter 3 database join ruby-on-rails

这是一个单独的问题,但它与之前的问题有关:使用Active Scaffold在Rails中加入三列.总结一下:Rails会自动查找两列连接表,但对于三列连接表则不会这样做.我已经尝试了上一个问题中的建议,但它归结为:

如果你有模型Project,Employee,Role,并且每个模型与其他两个都有一个habtm关系,rails会分别完成每个关系,但不能作为一个整体.

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
Run Code Online (Sandbox Code Playgroud)

为项目重复,角色如下

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
Run Code Online (Sandbox Code Playgroud)

我的问题是这个,因为rails会查找employees_projects, projects_roles,employees_roles但是没有employees_projects_roles办法将这些名称别名化为真正的表名,并且仍然允许数据库中的CRUD功能(MySQL或PostgreSQL)?

[编辑]哎呀.在我喝足够的咖啡之前,我必须停止公开回答和提问.将注释掉的部分从hmt更改为habtm.包含注释掉的代码部分,以反映我尝试过的各种选项.

jdl*_*jdl 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
Run Code Online (Sandbox Code Playgroud)

如果是这样,您只需指定要与您的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
Run Code Online (Sandbox Code Playgroud)