On Mar 4, 2010, at 12:58 PM, Michael Pavling wrote:
On 4 March 2010 17:30, Hassan Schroeder <[email protected]>
wrote:
Similarly, you can now no longer alter your models, because some
migrations rely on the operation of the model at that "point in
time"
Likewise, sorry, that makes zero sense to me. I can't alter a model
because it was altered before? What??
Maybe an example would help...
Yesterday I created this model and it's migration:
class Post < ActiveRecord::Base
end
take that model...
class CreatePosts < ActiveRecord::Migration
and put it right here INSIDE the migration class
def self.up
create_table :posts do |t|
t.string :summary
t.string :user_id
t.timestamps
end
# default record for Posts
Post.reset_column_information
Post.create(:name => "My First Post", :user_id => 1)
end
def self.down
drop_table :posts
end
end
Today I decide that I need to have an "expired flag" on my posts, and
it's required, so I create a new migration and edit my model:
class Post < ActiveRecord::Base
validates_presence_of :expires
end
class AlterPostsAddExpired < ActiveRecord::Migration
def self.up
add_column :posts, :expires, :datetime
end
def self.down
remove_column :posts, :expires
end
end
But now, when I roll back my migrations and try to roll them forward
again, the "create" breaks because the "point in time" Post record
*didn't* require an "expires" value (or indeed, even have a field for
it!).
As Rob says, the way around this is to duplicate the model code (or at
least the minimum you need to achieve your result) in the migration -
but this is a smelly, non-DRY, and non-testable way of putting data in
the tables (remember where I said it was "deliberately awkward" to do)
- when the alternative is to use a seed or seed-fu (like, 30 seconds
work), I can't believe you're making me go through these hoops to show
you how bad a practice it is to put data in your migrations
:-/
You can have the same kind of problems in migrations that aren't
trying to seed data, but just do the kind of things to change existing
data that happen in the real world.
I've helped projects that got themselves into trouble with too many
migrations happening between production deployments and the *set* of
migrations can't even be run forward during the deploy.
-Rob
Rob Biedenharn http://agileconsultingllc.com
[email protected]
--
You received this message because you are subscribed to the Google Groups "Ruby on
Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.