简体   繁体   中英

Is it possible to invoke change_table from command line with ActiveRecord migrations?

It is possible to invoke a create_table syntax in a migration from command line by specifying the keyword 'Create' in the migration name:

rails g migration CreateMyTables name:string

This will create a migration with the following content:

class CreateMyTables < ActiveRecord::Migration
  def change
    create_table :my_tables do |t|
      t.string :name
    end
  end
end

I would like to accomplish the same but with the 'Change' keyword. So from the command line I would run:

rails g migration ChangeMyTables user:references

This is what I got:

class ChangeMyTables < ActiveRecord::Migration
  def change
  end
end

This is what I would expect:

class ChangeMyTables < ActiveRecord::Migration
  def change
    change_table :my_tables do |t|
      t.references :user, index: true
    end
  end
end

There is a way to add the reference column from command line:

rails g migration AddUserToMyTable user:references

Note : to add the column to the table we use the convention Add[column]To[table] for renaming the migration.

The result will be similar to:

class AddUserToMyTable < ActiveRecord::Migration[5.2]
  def change
    add_reference :my_tables, :user, foreign_key: true
  end
end

Note: foreign_key: true will create the index for you.

Learn more about add_reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM