instance method
add_index
Ruby on Rails 3.2.22.5
Since v2.2.3Signature
add_index(table_name, column_name, options = {})
Adds a new index to the table. column_name can be a single Symbol, or an Array of Symbols.
The index will be named after the table and the column name(s), unless you pass :name as an option.
Examples
Creating a simple index
add_index(:suppliers, :name)
generates
CREATE INDEX suppliers_name_index ON suppliers(name)
Creating a unique index
add_index(:accounts, [:branch_id, :party_id], :unique => true)
generates
CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
Creating a named index
add_index(:accounts, [:branch_id, :party_id], :unique => true, :name => 'by_branch_party')
generates
CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
Creating an index with specific key length
add_index(:accounts, :name, :name => 'by_name', :length => 10)
generates
CREATE INDEX by_name ON accounts(name(10)) add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15})
generates
CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
Note: SQLite doesn’t support index length
Creating an index with a sort order (desc or asc, asc is the default)
add_index(:accounts, [:branch_id, :party_id, :surname], :order => {:branch_id => :desc, :part_id => :asc})
generates
CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
Note: mysql doesn’t yet support index order (it accepts the syntax but ignores it)
Parameters
-
table_namereq -
column_namereq -
optionsopt = {}
Source
# File activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb, line 350
def add_index(table_name, column_name, options = {})
index_name, index_type, index_columns = add_index_options(table_name, column_name, options)
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})"
end
Defined in activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb line 350
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionAdapters::SchemaStatements