Search code examples
ruby-on-railsdatabase-migrationrails-migrations

Change foreign key column name in rails


I have a Project migration class like this:

class CreateProjects < ActiveRecord::Migration
 def change
  create_table :projects do |t|
   t.string :title
   t.text :description
   t.boolean :public
   t.references :user, index: true, foreign_key: true

   t.timestamps null: false
  end
 end
end

It creates a column name user_id in projects table but I want to name the column owner_id so I can use project.owner instead of project.user.


Solution

  • You can do it two ways:

    #app/models/project.rb
    class Project < ActiveRecord::Base
       belongs_to :owner, class_name: "User", foreign_key: :user_id
    end 
    

    OR

    $ rails g migration ChangeForeignKeyForProjects
    
    # db/migrate/change_foreign_key_for_projects.rb
    class ChangeForeignKeyForProjects < ActiveRecord::Migration
       def change
          rename_column :projects, :user_id, :owner_id
       end
    end
    

    then:

    $ rake db:migrate