从模式生成Rails迁移

11

我正在创建一个新的Rails应用程序,它将与现有模式一起使用。我已经获得了这个模式的SQL,但我想创建Rails迁移来填充开发中的数据库。这个模式并不是过于复杂,大约有20个表,但我不想通过手动创建迁移浪费时间并冒着错别字的风险。

有没有一种方法可以根据模式的SQL生成Rails迁移?


不得不承认,很难找到这个的副本:https://dev59.com/RU3Sa4cB1Zd3GeqPwIw7 - Spyros
完全同意 - 这是另一个问题的重复。 - François Beausoleil
1
是的,抱歉,这是一个重复的问题。我进行了搜索,但找不到类似的答案。 - AaronThomson
2个回答

15

当然,将您的应用程序连接到您的数据库,然后运行

rake db:schema:dump

这将为您提供一个包含所有定义的db/schema.rb。现在,您有了那个db/schema.rb,只需将声明中的内容复制到新的迁移中即可。我以前就这么做过,效果非常好。


5

我更喜欢使用SQL执行调用来编写初始迁移的up方法:

class InitialDbStructure < ActiveRecord::Migration
    def up
        execute "CREATE TABLE abouts (
            id INTEGER UNSIGNED AUTO_INCREMENT,
            updated_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            created_at TIMESTAMP,

            title VARCHAR(125),
            body MEDIUMTEXT,

            CONSTRAINT PK_id PRIMARY KEY (id),
            INDEX ORDER_id (id ASC)
            ) ENGINE=InnoDB;"
        end

注意事项

  • You will find, particularly if you are often rebuilding and repopulating tables (rake db:drop db:create db:schema:load db:fixtures:load), that execute statements run far faster than interpreted Ruby syntax. For example, it takes over 55 seconds for our tables to rebuild from Rails migrations in Ruby syntax, whereas execute statements re-generate and re-populate our tables in 20 seconds. This of course is a substantial issue in projects where initial content is regularly revised, or table specifications are regularly revised.

  • Perhaps of equal importance, you can retain this rebuild and repopulate speed by maintaining a single original migration in executed SQL syntax and re-executing migrations (of that single file) by first gutting your schema.rb and then running rake db:reset before re-populating your tables. Make sure you set :version => 0, so that you will get a new schema, faithful to your migration:

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

我不喜欢在迁移中使用原始SQL,因为ORM无法包装不同的数据库。虽然速度较慢,但您可以获得可移植性。也许这并不是每个人都需要考虑的成本。 - New Alexandria
2
实际上,这个想法干扰了您选择数据库并利用其优点所必需的练习。例如,如果您打算和需要依赖于Postgres的BigSerial类型,那么您必须勇敢面对。当然,Ruby的意图是隐藏所有那些“复杂性”,仿佛漠不关心和难以接近是美德一样。因此,我们已经“获得帮助”(雇佣的人)来隐藏我们有意使用数据类型,仿佛他们在帮我们一个忙! - mike montagne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接