加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:07:41 所属栏目:百科 来源:网络整理
导读:我有一个像这样的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:
我有一个像这样的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读