简体   繁体   中英

Ruby on Rails: Migrations: how do I merge to tables into a new table?

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM