简体   繁体   English

Rails:使用迁移创建关联

[英]Rails: Using migrations to create an association

I have a User table and a Product table. 我有一个User表和一个Product表。 There is a has_many :products and a belongs_to :user relationship. 有一个has_many :products和一个属belongs_to :user关系。 I defined the Product and User models correctly...my question is about setting up the migration so that the schema comes out right. 我正确定义了产品和用户模型...我的问题是关于设置迁移,以便使模式正确无误。 I tried and this was the extra line in the schema that i got. 我试过了,这是我得到的架构中的额外一行。

add_index "product", ["user_id"], name: "index_product_on_user_id"

I then had a look online and instead of add_index other code had add_reference...does that matter? 然后,我在网上看了一下,除了add_index以外,其他代码都具有add_reference ...这有关系吗? And not sure about the name: "index_product_on_user_id". 并且不确定名称:“ index_product_on_user_id”。 Thanks! 谢谢!

add_reference adds the required columns and (optionally) creates an index whereas add_index just creates the index, so if you want to use add_index you need to create the column separately. add_reference添加所需的列并(可选)创建索引,而add_index仅创建索引,因此,如果要使用add_index ,则需要单独创建列。

You almost never need to set the index name - it doesn't affect how the index works or is used (one case is where the autogenerated index name exceeds the maximum index length). 您几乎不需要设置索引名称-它不会影响索引的工作方式或使用方式(一种情况是自动生成的索引名称超过了最大索引长度)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM