Difference Between Foreign Key Constraints and Links in Rails

Is there a difference between using t.references and executing an SQL command to create a foreign key relationship between the products and category tables, as shown below? In other words, are these two different ways to do the same thing, or am I losing nothing here?

 class ExampleMigration < ActiveRecord::Migration def up create_table :products do |t| t.references :category end #add a foreign key execute <<-SQL ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id) SQL add_column :users, :home_page_url, :string rename_column :users, :email, :email_address end def down rename_column :users, :email_address, :email remove_column :users, :home_page_url execute <<-SQL ALTER TABLE products DROP FOREIGN KEY fk_products_categories SQL drop_table :products end end 
+6
source share
2 answers

I found something interesting on this page.

http://railsforum.com/viewtopic.php?id=17318

From the comment:

Rails does not use foreign keys to perform its internal tasks. This is because some db, such as sqlite, does not allow the use of foreign keys in its tables. Therefore, Rails does not provide a helper for creating a foreign key.

There is also a gem foreigner for adding foreign keys to the database table. What creates a FOREIGN KEY constraint in Ruby on Rails 3?

0
source

This is not the same thing. By default, Rails does not use foreign keys in the database. Instead, links when created from the command line also create a regular index, for example:

 add_index :products, :category_id 

Update:

Rails 5 is actually doing the same now. So, to answer the original question: both are currently the same.

+2
source

Source: https://habr.com/ru/post/920770/


All Articles