据我所知,默认情况下会创建 id
字段,同时也是: PRIMARY KEY(
id 。
外键怎么样?
code>商店和产品
表以及下列关联:
<$ p $购物车:has_many:产品
产品:belongs_to:shop
在产品
中也有:
$ p $ t $整数shop_id
这就是外键,还有:
add_index(products,shop_id)
$ b $但是,如果我导出数据库,我只看到:
$ p $ key $ index_products_on_shop_id`(shop_id`)
我应该怎么做才能添加
$ b $ p>?解决方案您可以使用 gem将外键添加到您的应用程序。要开始添加以下内容到您的
Gemfile
gemforeigner
之后,您可以轻松地在迁移中添加外键,如下所示:
add_foreign_key:products,:shops
这会将
product.shop_id
添加到shop.id
中。请参阅文档以获取更多选项,如不同名称的键或自引用表。I understand that by default the
id
field is created and also:PRIMARY KEY (
id)
.How about the foreign key ?
I have
Shops
andProducts
tables and the following associations:Shop: has_many :products Product: belongs_to :shop
In
Product
I have also:t.integer "shop_id"
which is meant to be the foreign key, and also:
add_index("products", "shop_id")
However, if I export the database I see only:
KEY `index_products_on_shop_id` (`shop_id`)
What should I do in order to add
FOREIGN KEY (`shop_id`) REFERENCES Shop(`id`)
?
解决方案
You can use the foreigner gem for adding foreign keys to your application. To get started add the following to your Gemfile
gem "foreigner"
After that you can easily add foreign keys in your migration like so:
add_foreign_key :products, :shops
This would add a foreign from product.shop_id
to shop.id
. See the documentation for more options like differently named keys or self-referencing tables.
这篇关于在Ruby on Rails 3中创建FOREIGN KEY约束是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!