Possible to generate a migration for a model?
I already have a user model created, with all the properties I want.
Now I want to run
rails g scaffold users
but ofcourse it won't work b/c there is already a user model.
Is it 开发者_如何学Gopossible for me to generate a migration for the current user model (generate meaning create a migration script with the current model so I can re-run it later).
This way I can then destory the model, run the scaffold, then run the migration with the old columns that I setup earlier.
possible?
You can create a migration manually by hand using rails generate migration
. Here's the output of that function's help:
Usage:
rails generate migration NAME [field:type field:type] [options]
Options:
-o, --orm=NAME # Orm to be invoked
# Default: active_record
Runtime options:
-f, [--force] # Overwrite files that already exist
-p, [--pretend] # Run but do not make any changes
-q, [--quiet] # Supress status output
-s, [--skip] # Skip files that already exist
Description:
Create rails files for migration generator.
This might happen when you are working with a model that is not database-backed, then you decide you want it to be, and extend ActiveRecord::Base
and realized there is no table. I'd pop in to Rails console, and look at the methods on the class. You can print the setter methods out like this:
>> y Model.instance_methods(false).grep /\=/ # "Model" is the name of your class
Then I'd create a new migration like normal and define the columns with their types. e.g. if your Model has a name column of type string, rails g migration Model name:string
. You might want to delete some of the generated files. If it doesn't work because it does a name match, I'd check if there is a force option, or I'd temporarily rename my existing model class, then name it back after the migration is generated.
精彩评论