What creates the FOREIGN KEY constraint in Ruby on

2019-02-07 06:16发布

问题:

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

How about the foreign key ?

I have Shops and Products 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`)

?

回答1:

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.