user1120144
user1120144

Reputation:

How to generate a schema file from migration files?

I have a simple ruby project that uses ActiveRecord as an ORM (without Rails). I created a few migration files for all of my tables and now I'm searching how to use them witouht Rails. Here's an example:

class CreateCategoriesTable < ActiveRecord::Migration
  def up
    create_table :categories do |t|
      t.integer :id, null: false
      t.string :name, null: false
    end
  end

  def down
    drop_table :categories
  end
end

And in my main file I run the migration using:

CreateCategoriesTable.new.migrate :up

However, if I have the db (its a sqlite db in a file) this migration causes an exception (the table already exists). So, how can I run all my migrations (or how to generate a schema file and then how to run it?) only then they are needed, e.g. the first time and then only when something has changed?

Upvotes: 1

Views: 109

Answers (1)

clang1234
clang1234

Reputation: 1714

This github repo might be useful to you.

The naming scheme for migrations is actually fairly important. Which migrations have been ran is kept track in a table called *schema_migrations*. Here's an example from postgres:

 Table "public.schema_migrations"
 Column  |          Type          | Modifiers 
---------+------------------------+-----------
 version | character varying(255) | not null
 Indexes:
 "unique_schema_migrations" UNIQUE, btree (version)

development=# select * from schema_migrations;
    version     
----------------
20130206231627
(1 row)

In addition schema.rb can keep track of it's current version

ActiveRecord::Schema.define(:version => 20130206231627) do
  ...
end

Upvotes: 1

Related Questions