如何从迁移文件生成模式文件?

时间:2013-02-08 22:22:12

标签: ruby activerecord

我有一个简单的ruby项目,它使用ActiveRecord作为ORM(没有Rails)。我为我的所有表创建了一些迁移文件,现在我正在搜索如何在Rails中使用它们。这是一个例子:

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

在我的主文件中,我使用以下命令运行迁移:

CreateCategoriesTable.new.migrate :up

但是,如果我有db(它是文件中的sqlite数据库),则此迁移会导致异常(表已存在)。那么,我怎样才能运行我的所有迁移(或者如何生成模式文件然后如何运行它?)只有这样才需要它们,例如,第一次,然后才发生变化?

1 个答案:

答案 0 :(得分:1)

This github repo可能对您有用。

迁移的命名方案实际上非常重要。运行了哪些迁移将在名为* schema_migrations *的表中进行跟踪。这是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)

另外,schema.rb可以跟踪它的当前版本

ActiveRecord::Schema.define(:version => 20130206231627) do
  ...
end
相关问题