method names in Rails migrations
I'm using Agile Web Development with Rails to learn about Rails. In an early chapter, the author created scaffolding and then started looking at the Migration. In his Migration, there is an "up" and and "down" method, whereas I only have a "change" method in my Migration. The author is using Rails 3.05 (or something like that) and I am using 3.1, however, I don't think that's the explanation, because using another book but same version of Rails I remember creating a migration that had the "up" and "down" methods...
So, two questions,
a) What's the reason why I have different method names in my migration?
b) is it going to affect functionality?
My Migration
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string : title
t.text :description
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
end
Books Migration
class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.string :title
t.text :descr开发者_JS百科iption
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
def self.down
drop_table :products
end
end
Rails 3.1 did away with both the "up" and "down" part of migrations. Now they are called "reversible migrations" that use the change method. So your first code example is correct for Rails 3.1, second is correct for 3.0.x and earlier. Here are the change notes for 3.1 that skim over this update:
https://gist.github.com/958283
The important line: Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's change method instead of the ordinary up and down methods.
The update makes sense if you think about it... you no longer have to define all the steps to "up" your database as well as type out the same steps in reverse to "down" your database. The change method is smart enough to go back and forth given the singe set of instructions.
To answer your second question, no it won't change how the migration works. It will still update your data store per your instructions, keep track of the migration, etc. It's just a more efficient way of describing those changes to your Model.
Same code really, just more dry (and slightly less customizeable).
Theres a good description here: http://edgerails.info/articles/what-s-new-in-edge-rails/2011/05/06/reversible-migrations/index.html
精彩评论