you are here: codestackercodes [RSS]import sql files into migrations

import sql files into migrations

it's a small how to import a file in migrations.

from: http://code-ronin.com/articles/rails-migrations-directly-import-sql

# first, create the method import_sql:


class ActiveRecord::ConnectionAdapters::MysqlAdapter
  def import_sql(file)
    conf = ActiveRecord::Base.configurations[RAILS_ENV]
    sql_file = File.join(RAILS_ROOT, 'db', file + '.sql')
    cmd_line = "mysql -h "+conf["host"]+" -D "+conf["database"]+ " --user="+conf["username"]+" --password="+conf["password"]+" < "+sql_file
    raise Exception, "Error executing " + cmd_line unless system(cmd_line)    
  end
end


# create a migration. ex:


./script/generate migration sql_external_test

# save your sql file with sql commands in db/. migration's sample:


class SqlExternalTest < ActiveRecord::Migration
  def self.up
    import_sql("test")
  end

  def self.down
  end
end

Comments