ruby-on-railsrails-migrations

Is there a way to change column to foreign key?


I have an existing column project_id inside a table called contents. It is supposed to be a foreign_key that references a project in projects table. However, whoever set up the database created the contents table without setting project_id as foreign_key.

I tried to create a migration as:

def change
    add_reference :contents, :project
end

But this tries to add a column project_id which already exists.

My Question is, is there a way (using migration) to change the column project_id to foreign_key?


Solution

  • Rails 5+ allows you to add foreign_key constraints using migration

    add_foreign_key :contents, :projects, column: :project_id, #primary_key: "id"
    

    Aside of that, You do not need foreign key constraints for ActiveRecord to correctly map the relationships in migration, i.e foreign_key constraint can be set explicitly at model level too. To make faster retrieval add indexing on project_id using migration

    Example-

    class Content < ApplicationRecord
      belongs_to :project, class_name: 'Project', :foreign_key => "project_id"
    end
    
    class Project < ApplicationRecord
     has_many :contents, class_name: 'Content', :foreign_key => "project_id",  :dependent => :destroy
    end