开发者

Rails Migration with adding and removing reference

开发者 https://www.devze.com 2023-02-25 10:23 出处:网络
After cre开发者_运维知识库ating a migration file with rails generate migration AddClientToUser I can edit my migration file like so:

After cre开发者_运维知识库ating 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?


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.


that is right! and you could also go with:

  def self.down
      remove_column :users, :client_id
  end


After rails 4 you can do the following

class AddClientToUser < ActiveRecord::Migration
  def change
    add_reference :users, :client, index: true
  end
end

It will handle the up and the down for you, as well as creating a foreign key index. You can also use remove_reference to do the opposite.


With Rails 4 you can just type:

$ rails generate migration AddClientRefToUser client:references

in the console and this will make the same that Ryan said.

0

精彩评论

暂无评论...
验证码 换一张
取 消