Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write SQL in a migration in Rails

I have the following SQL which I need to do

CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users;  DROP TABLE cars_users;  ALTER TABLE cars_users2 RENAME TO cars_users; 

since I cannot use heroku dataclips to drop a table, I cannot use dataclips.

So I guess I need to do this in a migration.

How do I write this sql as a migration?

like image 559
Nick Ginanto Avatar asked Feb 13 '13 15:02

Nick Ginanto


People also ask

How Rails db Migrate works?

When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration.

How do I run a database migration in Ruby on Rails?

Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. Teams of developers − If one person makes a schema change, the other developers just need to update, and run "rake migrate".


2 Answers

For your up migration:

execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users;"  drop_table :car_users   rename_table :car_users2, :car_users   

and for down:

raise ActiveRecord::IrreversibleMigration 

Full migration:

class TheMigration < ActiveRecord::Migration     def up         execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * from cars_users;"          drop_table :car_users           rename_table :car_users2, :car_users       end      def down         raise ActiveRecord::IrreversibleMigration     end end 
like image 140
Tomdarkness Avatar answered Sep 22 '22 06:09

Tomdarkness


You could try to use the execute method.

Something like this (it's untested, some kind of brainchild)

class UpdateCarUserTable < ActiveRecord::Migration   def up     execute "CREATE TABLE cars_users2 AS SELECT DISTINCT * FROM cars_users"     execute "DROP TABLE cars_users"     execute "ALTER TABLE cars_users2 RENAME TO cars_users"   end 

As there is no equivalent down method, an ActiveRecord::IrreversibleMigration should be raised when trying to migrate down.

like image 29
ConcurrentHashMap Avatar answered Sep 22 '22 06:09

ConcurrentHashMap