Prev | Current Page 151 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

The change_column
method works just like the add_column method, except that it works on existing columns and
will change their data types instead of creating a new column. Most database engines will preserve
the existing data in a column, if it??™s possible.
change_column :address, :postal_code, :string
Indexing Columns
One of the important things that developers often forget to do is create indexes on their tables.
Indexes can dramatically decrease query times and should always be in place on often-queried
columns or groups of columns. Especially important are indexes on foreign keys, join tables,
type columns, and compound keys from polymorphic associations. They often go overlooked,
which adds a great deal of overhead to traversing relationships.
You can add an index with the add_index method. Indexes are placed on a table over one
or more columns. The add_index method takes a table name and either a column name or an
array of column names.
CHAPTER 3 ?–  SETTING UP YOUR DATABASE 54
add_index :cows, :farmer_id, :name => "index_on_cows_for_farmers"
add_index :ownerships, [:farmer_id, :tractor_id], :unique => true
Notice the :unique => true option.


Pages:
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163