Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between add_references and add_column in rails

 add_reference :books, :author
 add_column :books, :author_id, :integer

Here add references will create user_id column and add column is also creating user_id column in books table. What is the difference between them. What is the advantage of using references instead of column?

like image 549
Suresh Avatar asked Nov 22 '17 09:11

Suresh


People also ask

How do I add a reference column in rails?

When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.

Do you need foreign keys in Rails?

You do not need a foreign key constraints for ActiveRecord to correctly map the relationships. You can use validations to have the Rails app ensure data integrity.

How do you delete a column in Rails?

The change method can be used to drop a column in Rails 4 applications, but should not be used in Rails 3. I updated my answer accordingly. You can also use remove_column :table_name, :column_name, :type, :options within the change method, since if you specify the type reverting the migration is possible.


1 Answers

TLDR

#add_column is meant for adding a column like the name suggests.

#add_reference is meant as a shortcut for creating a column, index and foreign key at the same time.

Explanation

In your example the only difference is the index on the column that will be created by #add_reference that defaults to true.

add_reference :books, :author
# equals
add_column :books, :author_id, :integer
add_index :books, :author_id

But if you would take the following line:

add_reference :books, :author, foreign_key: true

It would also create a foreign key constraint.

Furthermore if you would like to have every author be able to publish only one book you can set the unique constraint through #add_reference by doing the following:

add_reference :books, :author, null: false, index: {unique: true}, foreign_key: true

This requires every book to have an author and restraints the authors to have a maximum of one book.

The same can be done using #add_column by doing the following:

add_column :books, :author_id, :integer, null: false
add_index :books, :author_id, unique: true
add_foreign_key :books, :authors
like image 70
3limin4t0r Avatar answered Oct 18 '22 09:10

3limin4t0r