Changing the name of a foreign key column in rails

I have a migration class project 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 

it creates the column name user_id in the project table, but I want to name the column owner_id, so I can use project.owner instead of project.user.

+5
source share
1 answer

You can do this in 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 

then

 $ rake db:migrate 
+4
source

Source: https://habr.com/ru/post/1242378/


All Articles