you are here: codestackercodes [RSS] → tag migrations [RSS]

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

[rails] create_table methods

  create_table :table do |t|
    t.column # adds an ordinary column. Ex: t.column(:name, :string)

    t.index # adds a new index.

    t.timestamps
    t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80)

    t.change_default # changes the column default value.

    t.rename # changes the name of the column.

    t.references
    t.belongs_to
    t.string
    t.text
    t.integer
    t.float
    t.decimal
    t.datetime
    t.timestamp
    t.time
    t.date
    t.binary
    t.boolean
    t.remove
    t.remove_references
    t.remove_belongs_to
    t.remove_index
    t.remove_timestamps
  end

migrations without timestamp

set in your environment.rb

config.active_record.timestamped_migrations = false
Displaying all 3 Code