What creates the FOREIGN KEY constraint in Ruby on Rails 3?

天大地大妈咪最大 提交于 2019-11-29 14:29:47

问题


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.



来源:https://stackoverflow.com/questions/4406075/what-creates-the-foreign-key-constraint-in-ruby-on-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!