Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Migration with adding and removing reference

After creating a migration file with rails generate migration AddClientToUser I can edit my migration file like so:

class AddClientToUser < ActiveRecord::Migration   def self.up     change_table :users do |t|       t.references :client     end   end    def self.down     change_table :users do |t|       t.remove :client_id     end   end end 

Is this the correct way to reverse the reference column added in the migration?

like image 834
Matt Connolly Avatar asked Apr 13 '11 12:04

Matt Connolly


People also ask

How do I add a reference to an existing table 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.

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.


1 Answers

Rails 4.2.1

rails g migration RemoveClientFromUsers client:references 

Will generate a migration similar:

class RemoveClientFromUser < ActiveRecord::Migration   def change     remove_reference :users, :client, index: true, foreign_key: true   end end 

In addition, one is at liberty to add another or other reference(s) by adding:

add_reference :users, :model_name, index: true, foreign_key: true 

within the very change method. And finally running rake db:migrate after saving the changes to the migration, will produce the desired results.

like image 181
MulleOne Avatar answered Sep 28 '22 01:09

MulleOne