Prev | Current Page 154 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

The ways that your models can change are many, from renaming a method to removing
an entire model altogether. You may not notice that a change has made it impossible to migrate
from migration zero to the latest one (e.g., if your database is at revision thirty and you changed
the model back around revision eight or nine), but you will notice when it comes time to deploy
to the production environment and an empty database.
As we mentioned, you might be inclined to create a migration like the following one to
populate the total column for our Orders model:
def self.up
add_column :orders, :total, :decimal
orders = Order.find(:all)
orders.each do |order|
CHAPTER 3 ?–  SETTING UP YOUR DATABASE 55
subtotal = 0
order.line_items.each do |line_item|
subtotal += line_item.quantity * line_item.price
end
order.total = subtotal
end
end
def self.down
remove_column :orders, :total
end
While this migration will work just fine, it is brittle. If the relationship between the Order
and LineItem models were to change or the quantity or price methods were to be removed,
the migration would not run.


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