Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change foreign key column name in rails

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

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.

like image 902
Azam Ikram Avatar asked Feb 05 '16 14:02

Azam Ikram


People also ask

What does Add_index do in rails?

It adds a multi-column index on columns one and two in resources table. The advantage of multi-column index is that it helps when you have a query with conditions on those multiple columns.

How do I add a foreign key in Ruby on Rails?

If you want you can always use add_index on the fields that you want as foreign keys. Or you can write your migrations in SQL or perhaps even force rails to do the foreign keys somehow. But the thing is you won't even look for a way to do it if you don't know rails is not doing itin the first place.

Do you need foreign keys in rails?

Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.

How do I add a reference column in rails?

When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.


1 Answers

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

then:

$ rake db:migrate
like image 133
Richard Peck Avatar answered Oct 10 '22 00:10

Richard Peck