Using STI in a migration


#1

I have some classes in my model which use STI and they work as expected
in the console. However, when I try to use them in a migration, I get
“uninitialized constant OfficePhone”, for example. Why doesn’t the
migration environment pick up the class defs? OfficePhone is defined in
the model/phone.rb. I put model :phone in the application.rb but my
migration just doesn’t seem to pick it up. Any ideas?

Steven


#2

On 6/10/06, Steven Talcott S. removed_email_address@domain.invalid wrote:

I have some classes in my model which use STI and they work as expected
in the console. However, when I try to use them in a migration, I get
“uninitialized constant OfficePhone”, for example. Why doesn’t the
migration environment pick up the class defs? OfficePhone is defined in
the model/phone.rb. I put model :phone in the application.rb but my
migration just doesn’t seem to pick it up. Any ideas?

You should put each subclass in its own file.
Phone should be in phone.rb
OfficePhone should be in office_phone.rb
etc.

That will let you get rid of the “model :phone” line, and also let you
use them without difficulty in migrations.


#3

Steven Talcott S. wrote:

I have some classes in my model which use STI and they work as expected
in the console. However, when I try to use them in a migration, I get
“uninitialized constant OfficePhone”, for example. Why doesn’t the
migration environment pick up the class defs? OfficePhone is defined in
the model/phone.rb. I put model :phone in the application.rb but my
migration just doesn’t seem to pick it up. Any ideas?

Steven

Along with what has already been mentioned:

“Don’t use your ActiveRecord models in your migrations or your life will
be miserable”

http://rails.techno-weenie.net/tip/2006/2/23/safely_using_models_in_migrations


#4

Very true. What you’ll find is that you can use OfficePhone as long as
you have already used Phone. Using Phone will cause phone.rb to be
loaded, which inadvertently also loads the definition of OfficePhone.

-Jonathan.


#5

Richard L. wrote:

Along with what has already been mentioned:

“Don’t use your ActiveRecord models in your migrations or your life will
be miserable”

http://rails.techno-weenie.net/tip/2006/2/23/safely_using_models_in_migrations

Thanks, I appreciate this and I too discovered that if I use the parent
class, I can get away with it.

I am writing a one-time series of migrations of a production database to
a new railsified schema so my model is evolving together with the
migrations and it helps me a lot to go back and re-run the series of
migrations constantly as I define the models. I certainly understand
the long term problem of keeping migrations around that use obselete
models but once I am in production, I will never need these migrations
again and will probably restart the migration counter at 0.

Thanks again for the tips! After cutover, I certainly will include any
required model defs in my migrations.

Steven