Change foreign key column name in rails

浪子不回头ぞ 提交于 2019-12-10 12:44:15

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/35226357/change-foreign-key-column-name-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!