Jon Snow
Jon Snow

Reputation: 11892

How to have two foreign key references to the same model in Active Record migration?

I'm using Rails 4. I have a User model. Now I want to create a new model called Following. The table followings would have the columns user_id and followed_user_id, which are foreign keys referencing records in the users table.

I have a Active Record migration to create the followings table, like

class CreateFollowings < ActiveRecord::Migration
    def change
        create_table :followings do |t|
            t.references :user, index: true, foreign_key: true
        end
    end
end

This will create the column user_id. How do I use the t.references syntax to create the followed_user_id column?

This isn't a question specific to Rails 4. So if this is possible in Rails 5 or Rails 3, please comment as well.

I'm not asking about how to set up the models. This question only concerns with the migration and setting up the table in the database.

Upvotes: 1

Views: 2145

Answers (2)

Thanh
Thanh

Reputation: 8624

It's impossible to use t.references syntax to create followed_user_id column without exists of followed_users table. Even if you can use that syntax, you still must set up associations in models.

What problem is if you create 2 columns and add index for them:

class TestFollowing < ActiveRecord::Migration
  def change
    create_table :following do |t|
      t.integer :user_id, index: true
      t.integer :folowed_user_id, index: true
    end
  end
end

Upvotes: 0

Nitin
Nitin

Reputation: 7366

Try change your migration like this:

class CreateFollowings < ActiveRecord::Migration
  create_table :followings do |t|
    def up
      t.references :user, index: true, foreign_key: true
      t.references :followed_user, index: true, foreign_key: true
    end
  end
end

And your model should also have same belongs_to relation in it. So add following association in your models.

Followeing Model:

class Following < ActiveRecord::Base
  belongs_to :user, class_name => 'User'
  belongs_to :followed_user, class_name => 'User'
end

User Model :

class User < ActiveRecord::Base
  has_many :users, :class_name => 'Following', :foreign_key => 'user_id'
  has_many :followed_users, :class_name => 'Following', :foreign_key => 'followed_user_id'
end

Another way to create foreign key below:

def change
  add_foreign_key :followings, :users, column: :followed_user_id
end

Api dock here.

Upvotes: 1

Related Questions