在rails中更改外键列名称

时间:2016-02-05 14:17:22

标签: ruby-on-rails database-migration rails-migrations

我有一个Project迁移类,如下所示:

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

它在项目表中创建了一个列名user_id,但我想将列命名为owner_id,因此我可以使用project.owner代替project.user

1 个答案:

答案 0 :(得分:9)

你可以用两种方式做到:

#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

然后:

$ rake db:migrate