微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/265154.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐