Prev | Current Page 155 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

Therefore, rather than using models directly in your migrations,
it is recommended that you use the execute method and ANSI-compliant SQL to perform
manipulations on the data directly, as shown in the following migration code:
def self.up
add_column :orders, :total, :decimal
ActiveRecord.execute("UPDATE orders LEFT OUTER JOIN line_items
SET orders.total=SUM(line_items.quantity * line_items.price) ON
orders.id=line_items.order_id")
end
def self.down
remove_column :orders, :total
end
Additionally, if your data manipulations rely on logic contained within your model, you
might go so far as to copy this logic directly into the migration file as a separate method. This
is because you cannot guarantee that that same code will still be present within the model the
next time that migration is run.
?– Note At the start of this chapter, we talked about migrations being a great, database-independent Active
Record feature, but here we seem to be going against that statement by including raw SQL into our migration
scripts.


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