Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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`)

?

like image 761
Misha Moroshko Avatar asked Dec 10 '10 05:12

Misha Moroshko


People also ask

How does foreign key work in Rails?

In Rails 5, adding foreign key constraints was added to have the database protect the integrity of associated data. Once a foreign key constraint is defined, your database will not allow you to remove records that are required by other tables.

What is the constraint of foreign key?

A foreign key joins a table to another table by referencing its primary key. A foreign key constraint specifies that the key can only contain values that are in the referenced primary key, and thus ensures the referential integrity of data that is joined on the two keys.

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.


1 Answers

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.

like image 136
Wolfgang Avatar answered Sep 25 '22 08:09

Wolfgang