从架构生成 Rails 迁移
我正在创建一个新的 Rails 应用程序,它将与现有架构一起使用。我已经获得了 SQL 模式,但我想创建 Rails 迁移来填充开发中的数据库。该架构并不太复杂,大约有 20 个表,但是我不想通过手动创建迁移来浪费时间和冒拼写错误的风险。
有没有办法根据模式的 SQL 生成 Rails 迁移?
I am creating a new Rails application which will work with an existing schema. I have been given the schema SQL but I want to create Rails migrations to populate the database in development. The schema is not overly complicated, with around 20 tables, however I don't want to waste time and risk typos by manually creating the migrations.
Is there a way to generate Rails migrations given a schema's SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,将您的应用程序连接到数据库,然后运行
这将为您提供一个包含所有定义的 db/schema.rb。现在您已经有了 db/schema.rb,只需将声明中的内容复制到新的迁移中即可。我以前做过这个,效果非常好。
Sure, connect your application to your database, then run
This will give you a db/schema.rb ready with all of your definitions. Now that you have that db/schema.rb, simply copy the contents within the declaration into a new migration. I've done this before, and it works just great.
我更喜欢简单地使用 SQL 执行调用编写初始迁移的 up 方法:
注释
您会发现,特别是如果您经常重建和重新填充表(rake db:drop db:create db:schema :load db:fixtures:load),执行语句的运行速度比解释的 Ruby 语法快得多。例如,我们的表需要 55 秒以上才能从 Ruby 语法中的 Rails 迁移重建,而执行语句在 20 秒内重新生成并重新填充我们的表。在定期修改初始内容或定期修改表规范的项目中,这当然是一个重大问题。
也许同样重要的是,您可以通过在执行的 SQL 语法中维护单个原始迁移并通过首先清除 schema.rb 然后运行 rake db 重新执行(该单个文件的)迁移来保持这种重建和重新填充速度:在重新填充表之前重置。确保设置 :version => 0,这样您将获得一个新的架构,忠实您的迁移:
I prefer to simply write the initial migration's up method with SQL execute calls:
NOTES
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: