DavidL
DavidL

Reputation: 915

Create a new table based on data from old table rails

I have a table users that contains details of each user. I'd like to create a new table containing only certain rows from the users table based on a condition (their age for example). How do I do this in rails ?

Upvotes: 1

Views: 165

Answers (1)

Marten
Marten

Reputation: 1356

You have to create a migration. In this migration you first have to create the new table and then you can choose between two options.

  1. You can use your models to read the data, use the ruby filter methods to filter the data sets and then transform the leftover models into your new ones and save them. But I would advise you against this, because you will not be able to execute this migration later, when you have deleted your current model. (The migration uses the old model to read the data but it is not available any more in the code)
  2. You use pure SQL:

    class XMigration < ActiveRecord::Migration
      def up
        execute <<-SQL
    CREATE TABLE new_table
    (id INTEGER AUTO_INCREMENT PRIMARY KEY, ...);
    
    INSERT INTO new_table (...)
    SELECT ... FROM old_table WHERE condition;
        SQL
      end
    
      def down
        raise ActiveRecord::IrreversibleMigration
      end
    end
    

Upvotes: 1

Related Questions