Skip to content

How to: Migrate from one model to another

jmarceli edited this page Jan 26, 2015 · 3 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 picture 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.not(picture: nil).find_each do |foo|
      photo = Photo.create(attachable: foo)
      # adjust foo.picture url prefix to suit your needs
      photo.image = File.new(File.join(Rails.root, '/public' + foo.picture.url))
      photo.save!
      # Haven't tried this but you should be able to do
      photo.image.recreate_versions!
    end
  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.

Clone this wiki locally