Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add foreign key in rails migration with different table name

Tags:

How can I assign different table name with adding foreign key. for e.g

I have a model like

class MyPost < ActiveRecord::Base   has_many :comments, class_name: PostComment end  class PostComment < ActiveRecord::Base   belongs_to :post, class_name: MyPost end 

Now i want to change my migration file like this:

class CreatePostComments < ActiveRecord::Migration   def change     create_table :post_comments do |t|      t.belongs_to :post, index: true      t.timestamps null: false     end     add_foreign_key :post, :class_name => MyPost   end end  

But it is not working. Migration is getting cancelled. How do I change my migration file to work with my model structure.

like image 517
Braham Shakti Avatar asked Aug 11 '15 08:08

Braham Shakti


People also ask

How do you add references to migration?

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.

How do I migrate a specific migration in rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.


2 Answers

You can pass in options for the foreign key as following:

class CreatePostComments < ActiveRecord::Migration   def change     create_table :post_comments do |t|       t.references :post, foreign_key: { to_table: :my_posts }, index: true       t.timestamps null: false     end   end end 

This is also true for the index option if you like to add a unique constraint:

t.references :post, foreign_key: { to_table: :my_posts }, index: { unique: true} 

By the way, references is an alias for belongs_to, or to be more exact, belongs_to is an alias for references.

See the details in the implementation rails 5.0.rc2 & rails 4.2

like image 67
Stefan Staub Avatar answered Sep 18 '22 20:09

Stefan Staub


It should look like this:

class CreatePostComments < ActiveRecord::Migration   def change     create_table :post_comments do |t|      t.belongs_to :post, index: true      t.timestamps null: false     end     add_foreign_key :post_comments, :my_posts, column: :post_id   end end  

Take a look at the documentation: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key

You use the column option when the column is named differently.

like image 44
lunr Avatar answered Sep 19 '22 20:09

lunr