在Rails中更改外键列名称 [英] Change foreign key column name in rails
本文介绍了在Rails中更改外键列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的 Project
迁移类:
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
它在项目表中创建了列名称 user_id
,但是我想将列命名为 owner_id
,所以我可以使用 project.owner
而不是 project.user
。
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
.
推荐答案
您可以通过两种方式进行操作:
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
然后:
$ rake db:migrate
这篇关于在Rails中更改外键列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文