forked from carrierwaveuploader/carrierwave
-
Notifications
You must be signed in to change notification settings - Fork 2
How to: Migrate from one model to another
designwaves edited this page Apr 23, 2012
·
2 revisions
I was finding it hard to figure out how to migrate from one model to another. My goal was to take the image filename/identifier from my Foo Model and move it to the Photo Polymorphic Model without having to deal with the mounted serialization column issues. Here is what I figure out would work to do this
# Foo Model
class Foo < ActiveRecord::Base
# has image column "test.jpg" and moving to Photo model
end
#Photo Model
class Photo < ActiveRecord::Base
mount_uploader :image, ImageUploader
belongs_to :attachable, :polymorphic => true
def attachable?
!!self.attachable
end
end
# Using a Migration to move the image column to the Photo Model
class MoveFooPhotosToPhotosModel < ActiveRecord::Migration
def self.up
Foo.where("image IS NOT NULL").all.each{ |foo|
photo = Photo.create(:attachable => foo)
photo.write_uploader(:image, foo.image)
photo.save!
# Haven't tried this but you should be able to do
photo.image.recreate_versions!
}
end
def self.down
end
end
You are now left with the columns moved to the new model, so you might have to recreate_versions! or run other migrations but this will move the column data for you to the new model.