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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With