Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails migration: t.references with alternative name?

People also ask

How do you name migration in rails?

Migrations should be: Camel cased or Snake cased. start with an action (i.e. create, add, remove, etc) The name of the table should be the last word and it should be plural.

What does T references do?

t. references tells the database to make a column in the table. foreign_key: true tells the database that the column contains foreign_key from another table. belongs_to tells the Model that it belongs to another Model.

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.

What is Add_index in rails migration?

add_index(table_name, column_name, options = {}) public. Adds a new index to the table. column_name can be a single Symbol, or an Array of Symbols. The index will be named after the table and the column name(s), unless you pass :name as an option.


You can do this all in the initial migration/column definition (at least currently in Rails 5):

t.references :transferable_as, index: true, foreign_key: {to_table: :courses}
t.references :same_as, index: true, foreign_key: {to_table: :courses}

You can do it this way:

create_table :courses do |t|
  t.string :name
  t.references :transferrable_as
  t.references :same_as
  t.timestamps
end

or using t.belongs_to as an alias for t.references

You can't add foreign_key: true to those two references lines. If you want to mark them as foreign keys at the database level you need to have a migration with this:

add_foreign_key :courses, :courses, column: :transferrable_as_id
add_foreign_key :courses, :courses, column: :same_as_id

Update

In Rails 5.1 and above you can add the foreign key in the migration in the create_table block like this:

create_table :courses do |t|
  t.string :name
  t.references :transferrable_as, foreign_key: { to_table: 'courses' }
  t.references :same_as, foreign_key: { to_table: 'courses' }
  t.timestamps
end

As an added answer to this question -- the Model should have the following line to complete the association:

    belongs_to :transferrable_as, class_name: "Course"
    belongs_to :same_as, class_name: "Course"

I think this thread has a different more Rails-ish way: Scaffolding ActiveRecord: two columns of the same data type

In the migration:

t.belongs_to :transferrable_as

t.belongs_to :same_as


I don't think references accepts the :as option, but you can create your columns manually...

create_table :courses do |t| 
  t.string  :name 
  t.integer :course1_id
  t.integer :course2_id 
  t.timestamps 
end