Ruby-on-rails 生成迁移 - 创建连接表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17765249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate migration - create join table
提问by gotqn
I have looked through many SOand googleposts for generating migration of join table for has many and belongs to manyassociation and nothing work.
我经历了许多期待SO和google职位产生连接表的迁移has many and belongs to many协会并没有什么工作。
All of the solutions are generating a empty migration file.
所有解决方案都生成一个空的迁移文件。
I am using rails 3.2.13and I have two tables: security_usersand assignments. These are some of things I have try:
我正在使用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
Can anyone tell how to create a join table migration between two tables?
谁能告诉如何在两个表之间创建连接表迁移?
采纳答案by Powers
Run this command to generate the empty migration file (it is not automatically populated, you need to populate it yourself):
运行此命令生成空迁移文件(不会自动填充,需要自己填充):
rails generate migration assignments_security_users
Open up the generated migration file and add this code:
打开生成的迁移文件并添加以下代码:
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
Then run rake db:migratefrom your terminal. I created a quiz on many_to_many relationshipswith a simple example that might help you.
然后rake db:migrate从你的终端运行。我用一个可能对您有所帮助的简单示例创建了一个关于 many_to_many 关系的测验。
回答by andrewcockerham
To autopopulate the create_join_table command in the command line, it should look like this:
要在命令行中自动填充 create_join_table 命令,它应该如下所示:
rails g migration CreateJoinTableProductsSuppliers products suppliers
For a Product model and a Supplier model. Rails will create a table titled "products_suppliers". Note the pluralization.
对于产品模型和供应商模型。Rails 将创建一个名为“products_suppliers”的表。注意复数。
(Side note that generationcommand can be shortened to just g)
(旁注,generation命令可以缩短为 just g)
回答by Prakash Raman
I usually like to have the "model" file as well when I create the join table. Therefore I do.
当我创建连接表时,我通常也喜欢拥有“模型”文件。因此我愿意。
rails g model AssignmentSecurityUser assignments_security:references user:references
回答by Cody Elhard
I believe this would be an updated answer for rails 5
我相信这将是 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

