Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between foreign key constraint and references in Rails

Is there any difference between using t.references and executing SQL command to create foreign key relationship between products and category table as shown below? In other words, are the two different ways of doing the same thing or am I missing anything 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
like image 839
shailesh Avatar asked Jul 18 '12 05:07

shailesh


1 Answers

They're not the same thing. Rails by default doesn't enforce foreign keys in the database. Instead, references when creating from the command line also creates a regular index, like this:

add_index :products, :category_id

Update:

Rails 5 actually does exactly the same thing now. So, to answer the original question: Nowadays, both are the same.

like image 88
Pedro Nascimento Avatar answered Nov 18 '22 21:11

Pedro Nascimento