views:

17

answers:

3

i have two tables attachments:

name, doc_name, doc_type, doc_size, cat

and media:

name, doc_name, doc_type, doc_size, cat

how do I write a migration file such that it takes all the entries from both tables and puts them into a new Files table?

+1  A: 
class MergeAttachmentsMediaToFiles < ActiveRecord::Migration
  def self.up
    create_table :files do |t|
      t.column :name, :string
      # ...
    end

    Attachment.find(:all).each do |attachment|
      File.create(:name => attachment.name,
                  :doc_name => attachment.doc_name,
                  :doc_type => attachment.doc_type,
                  :doc_size => attachment.doc_size,
                  :cat => attachment.cat)
    end

    # do similar for Media
  end


end
Terry Lorber
+1  A: 

I would accomplish this primarily with SQL. Making some assumptions about your data types:

class CreateFiles < ActiveRecord::Migration

 def self.up
  create_table :files do |t|
   t.string :name
   t.string :doc_name
   t.string :doc_type
   t.integer : doc_size
   t.string :cat
  end

  execute ("insert into files select * from attachments");
  execute ("insert into files select * from media");
 end

 def self.down
  drop_table :files
 end

end
meagar
I swear I didn't copy. I submitted right after the "2 New Answers" popped up. +1 for good minds thinking alike. :)
treefrog
+1  A: 

I know the SQL to do it.

    def self.up
          create_table :files do |t|
            t.string  :name
            t.string  :doc_name
            t.string  :doc_type
            t.string  :doc_size
            t.string :cat
          end

          execute "INSERT INTO create_table(name, doc_name, doc_type, doc_size, cat)
                   SELECT name, doc_name, doc_type, doc_size, cat FROM attachments
                   UNION
                   SELECT name, doc_name, doc_type, doc_size, cat FROM media"

          drop_table :attachments
          drop_table :media
end

Not tested but should work.

treefrog
I don't know if I'd drop the old tables... awfully hard to roll back that migration and get your old data back.
meagar
Sometimes it's good to live on the edge. :) But that's true, I only put it in in the name of completeness.
treefrog