本文介绍了在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 endOR
$ 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中更改外键列名称
发布评论