更改 rails 中的外键列名称

Change foreign key column name in rails

我有一个 Project 迁移 class 是这样的:

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

它在项目 table 中创建了一个列名称 user_id 但我想将该列命名为 owner_id 以便我可以使用 project.owner 而不是 project.user .

您可以通过两种方式进行:

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

$ 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