我查看了许多SO
和google
帖子,为has many and belongs to many
协会生成连接表的迁移,没有任何工作。
所有解决方案都生成一个空的迁移文件。
我正在使用rails 3.2.13
,我有两张桌子:security_users
和assignments
。这些是我尝试过的一些事情:
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
任何人都可以告诉如何在两个表之间创建连接表迁移吗?
运行此命令以生成空迁移文件(它不会自动填充,您需要自己填充):
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
。我用一个可能对你有帮助的简单例子创建了a quiz on many_to_many relationships。
要在命令行中自动填充create_join_table命令,它应如下所示:
rails g migration CreateJoinTableProductsSuppliers products suppliers
对于产品型号和供应商型号。 Rails将创建一个名为“products_suppliers”的表。注意复数。
(注意,generation
命令可以缩短为g
)
我通常喜欢在创建连接表时使用“模型”文件。所以我这样做。
rails g model AssignmentSecurityUser assignments_security:references user:references
我相信这将是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