instance method change_table

Ruby on Rails 3.1.12

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

change_table(table_name, options = {})

A block for changing columns in table.

Example

# 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(11), ADD COLUMN birthdate DATETIME …

Defaults to false.

Examples
Add a column
change_table(:suppliers) do |t|
  t.column :name, :string, :limit => 60
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(integer) 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(integer) 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 transformation

Parameters

table_name req
options opt = {}
Source
# File activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb, line 238
      def change_table(table_name, options = {})
        if supports_bulk_alter? && options[:bulk]
          recorder = ActiveRecord::Migration::CommandRecorder.new(self)
          yield Table.new(table_name, recorder)
          bulk_change_table(table_name, recorder.commands)
        else
          yield Table.new(table_name, self)
        end
      end

Defined in activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb line 238 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::ConnectionAdapters::SchemaStatements

Type at least 2 characters to search.

↑↓ navigate · open · esc close