instance method
change_table
Ruby on Rails 7.2.3
Signature
change_table(table_name, base = self, **options)
A block for changing columns in table.
# change_table() yields a Table instance
change_table(:suppliers) do |t|
t.column :name, :string, limit: 60
# Other column alterations here
end
The options hash can include the following keys:
:bulk-
Set this to true to make this a bulk alter query, such as
ALTER TABLE `users` ADD COLUMN age INT, ADD COLUMN birthdate DATETIME ...Defaults to false.
Only supported on the
MySQLandPostgreSQLadapter, ignored elsewhere.
Add a column
change_table(:suppliers) do |t|
t.column :name, :string, limit: 60
end
Change type of a column
change_table(:suppliers) do |t|
t.change :metadata, :json
end
Add 2 integer columns
change_table(:suppliers) do |t|
t.integer :width, :height, null: false, default: 0
end
Add created_at/updated_at columns
change_table(:suppliers) do |t|
t.timestamps
end
Add a foreign key column
change_table(:suppliers) do |t|
t.references :company
end
Creates a company_id(bigint) column.
Add a polymorphic foreign key column
change_table(:suppliers) do |t|
t.belongs_to :company, polymorphic: true
end
Creates company_type(varchar) and company_id(bigint) columns.
Remove a column
change_table(:suppliers) do |t|
t.remove :company
end
Remove several columns
change_table(:suppliers) do |t|
t.remove :company_id
t.remove :width, :height
end
Remove an index
change_table(:suppliers) do |t|
t.remove_index :company_id
end
See also Table for details on all of the various column transformations.
Parameters
-
table_namereq -
baseopt = self -
optionskeyrest
Source
# File activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb, line 504
def change_table(table_name, base = self, **options)
if supports_bulk_alter? && options[:bulk]
recorder = ActiveRecord::Migration::CommandRecorder.new(self)
yield update_table_definition(table_name, recorder)
bulk_change_table(table_name, recorder.commands)
else
yield update_table_definition(table_name, base)
end
end
Defined in activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb line 504
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionAdapters::SchemaStatements