在Rails中更改外键列名称

编程入门 行业动态 更新时间:2024-10-26 15:29:24
本文介绍了在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中更改外键列名称

本文发布于:2023-11-12 00:56:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580043.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   Rails   外键列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!