是什么在 Ruby on Rails 3 中创建了 FOREIGN KEY 约束? [英] What creates the FOREIGN KEY constraint in Ruby on Rails 3?
问题描述
我了解默认情况下会创建 id
字段,并且:PRIMARY KEY (
id)
.
I understand that by default the id
field is created and also: PRIMARY KEY (
id)
.
外键呢?
我有 Shops
和 Products
表以及以下关联:
I have Shops
and Products
tables and the following associations:
Shop: has_many :products
Product: belongs_to :shop
在 Product
我也有:
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`)
我应该怎么做才能添加
FOREIGN KEY (`shop_id`) REFERENCES Shop(`id`)
?
推荐答案
你可以使用 foreigner gem用于向您的应用程序添加外键.要开始添加以下内容到您的 Gemfile
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
这会将一个来自 product.shop_id
的外部添加到 shop.id
.有关更多选项,例如不同名称的键或自引用表,请参阅文档.
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 约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!