Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using rake db:migrate straight, vanilla SQL

What gotchas would be involved by using rake db:migrate to load vanilla SQL?

The business requirements that I am working with don't allow me to use the default Rails' migrations. But I still need to track changes, easily alter the database DDL, and the other things that Rails' migrations give you.

So a migration file would look like:

class AddDateToPost < ActiveRecord::Migration
  def self.up
    ActiveRecord::Base.connection.execute("ALTER TABLE `posts` ADD COLUMN date DATETIME NULL")
  end

  def self.down
    ActiveRecord::Base.connection.execute("ALTER TABLE `posts` DROP COLUMN date")
  end
end
like image 668
vrish88 Avatar asked Feb 08 '11 19:02

vrish88


People also ask

How does rake db migrate work?

A migration means that you move from the current version to a newer version (as is said in the first answer). Using rake db:migrate you can apply any new changes to your schema. But if you want to rollback to a previous migration you can use rake db:rollback to nullify your new changes if they are incorrectly defined.

What does rake db schema load do?

rake db:schema:load is great for the first time you put a system in production. After that you should run migrations normally. This also helps you cleaning your migrations whenever you like, since the schema has all the information to put other machines in production even when you cleaned up your migrations.

How do I migrate a database in Ruby?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.

What does rails generate migration do?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.


1 Answers

That's perfectly acceptable and there are no gotchas, as long as you feel confident that your up and down functions mirror each other. I would suggest doing the following for readability:

class AddDateToPost < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE `posts` ADD COLUMN date DATETIME NULL"
  end

  def self.down
    execute "ALTER TABLE `posts` DROP COLUMN date"
  end
end
like image 139
Pan Thomakos Avatar answered Oct 13 '22 23:10

Pan Thomakos