Rails migration: t.references with alternate name?

So, I have a create_table like this for courses at school:

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

but I want him to refer to two other courses, such as:

 has_many :transferrable_as # A Course has_many :same_as # Another Course 

Can I say the following?

 t.references :transferrable_as, :as=> :course 
+60
ruby-on-rails migration associations
May 29 '10 at 2:57
source share
5 answers

I think this thread has a different Rails-ish path: ActiveRecord forests: two columns of the same data type

In the process of migration:

t.belongs_to: transferrable_as

t.belongs_to: same_as

+11
May 29 '10 at 17:52
source share

You can do it as follows:

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

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

You cannot add foreign_key: true to these two lines of links. If you want to mark them as foreign keys at the database level, you need to migrate with this:

 add_foreign_key :courses, :courses, column: :transferrable_as_id add_foreign_key :courses, :courses, column: :same_as_id 
+61
Aug 10 '15 at 16:11
source share

You can do all this 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 } 
+52
Dec 17 '16 at 5:24
source share

I don't think references accepts the :as parameter, 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 
+3
May 29 '10 at 2:26 p.m.
source share

As an additional answer to this question: to complete the association, the model should have the following line:

  belongs_to :transferrable_as, class_name: "Course" belongs_to :same_as, class_name: "Course" 
+2
Jul 12 '16 at 10:12
source share



All Articles