Suresh
Suresh

Reputation: 151

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?

Upvotes: 5

Views: 3587

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21110

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

Upvotes: 9

Vishal
Vishal

Reputation: 7361

Both will generate the same columns when you run the migration.

The first command adds a belongs_to :author relationship in your Book model whereas the second does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the author_id column and it will use a model named Author to instantiate the specific author.

The first command also adds an index on the new author_id column.

Upvotes: 0

Related Questions