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`)
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With