是什么在 Ruby on Rails 3 中创建了 FOREIGN KEY 约束? [英] What creates the FOREIGN KEY constraint in Ruby on Rails 3?

查看:20
本文介绍了是什么在 Ruby on Rails 3 中创建了 FOREIGN KEY 约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解默认情况下会创建 id 字段,并且:PRIMARY KEY (id).

I understand that by default the id field is created and also: PRIMARY KEY (id).

外键呢?

我有 ShopsProducts 表以及以下关联:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆