75

我浏览了许多帖子以生成关联表的迁移,SO但没有任何效果。googlehas many and belongs to many

所有解决方案都生成一个空的迁移文件。

我正在使用rails 3.2.13,我有两个表:security_usersassignments. 这些是我尝试过的一些事情:

rails generate migration assignments_security_users

rails generate migration create_assignments_security_users

rails generate migration create_assignments_security_users_join_table

rails g migration create_join_table :products, :categories (following the official documentation)

rails generate migration security_users_assignments security_user:belongs_to assignments:belongs_to 

谁能告诉如何在两个表之间创建连接表迁移?

4

5 回答 5

189

要在命令行中自动填充 create_join_table 命令,它应该如下所示:

rails g migration CreateJoinTableProductsSuppliers products suppliers

对于产品模型和供应商模型。Rails 将创建一个名为“products_suppliers”的表。注意复数。

(旁注generation命令可以缩短为 just g

于 2013-12-19T03:16:45.863 回答
46

运行此命令生成空迁移文件(不会自动填充,需要自己填充):

rails generate migration assignments_security_users

打开生成的迁移文件并添加以下代码:

class AssignmentsSecurityUsers < ActiveRecord::Migration
  def change
    create_table :assignments_security_users, :id => false do |t|
      t.integer :assignment_id
      t.integer :security_user_id
    end
  end
end

然后rake db:migrate从您的终端运行。我用一个可能对您有所帮助的简单示例创建了一个关于 many_to_many 关系的测验。

于 2013-07-20T19:12:22.390 回答
34

当我创建连接表时,我通常也喜欢拥有“模型”文件。因此我愿意。

rails g model AssignmentSecurityUser assignments_security:references user:references
于 2016-07-28T10:51:51.597 回答
2

在rails中有用于连接表的嵌入式生成

rails g migration AddCityWorkerJoinTable cities:uniq workers

这会产生以下迁移

create_join_table :cities, :workers do |t|
  t.index [:city_id, :worker_id], unique: true
end

❗️ 注意:

  • 型号名称应按字母顺序排列
  • 只放在:uniq第一个参数上
于 2021-05-14T19:37:50.767 回答
1

我相信这将是 Rails 5 的更新答案

create_table :join_table_name do |t|
  t.references :table_name, foreign_key: true
  t.references :other_table_name, foreign_key: true
end
于 2019-03-21T14:19:32.527 回答