ruby-on-rails – 更改rails中的外键列名称

我有一个像这样的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.

解决方法

你可以用两种方式做到:
#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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...