27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

254 CHAPTER 10 Tracking state<br />

which define the colors of the label for this ticket. Later on, you’ll add a position field<br />

that you’ll use to determine the sort order of the states in the select box. Let’s create this<br />

State model and the associated migration by running this command:<br />

rails g model state name:string color:string background:string<br />

Before running this migration, you need to define a way that states link to comments<br />

and to tickets, but there are a couple of things worth mentioning beforehand. For<br />

comments, you want to track the previous state so you can display that a comment has<br />

changed the ticket’s state. For tickets, you want to track the state for which you’ll use a<br />

foreign key. With all of this in mind, let’s add these fields to the migration now. You<br />

also remove the timestamps call from within create_table because it’s not important<br />

when states were created or updated. When you’re done, the whole migration should<br />

look like the following listing.<br />

Listing 10.10 db/migrate/[date]_create_states.rb<br />

class CreateStates < ActiveRecord::Migration<br />

def up<br />

create_table :states do |t|<br />

t.string :name<br />

t.string :color<br />

t.string :background<br />

end<br />

add_column :tickets, :state_id, :integer<br />

add_index :tickets, :state_id<br />

add_column :comments, :state_id, :integer<br />

end<br />

def down<br />

drop_table :states<br />

remove_column :tickets, :state_id<br />

remove_column :comments, :state_id<br />

end<br />

end<br />

In this migration you use the add_index method to add a database index on the<br />

tickets table’s state_id field. By adding an index on this field, you can speed up<br />

queries made that search for this particular field. The side-effect of indexing is that it<br />

will result in slower writes and more disk space. It’s always important to have indexes<br />

on nonprimary-key fields 2 because of this great read speed increase.<br />

Let’s run this migration now by running these two commands:<br />

rake db:migrate<br />

rake db:test:prepare<br />

2 Primary key in this case is the id field that is automatically created for each model by create_table. Primary<br />

key fields are, by default, indexed.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!