Rails:schema.rb 有什么作用? [英] Rails: what does schema.rb do?
问题描述
我以前认为Rails
项目中的db/schema.rb
存储的是数据库schema,这样ActiveRecord
就能知道什么表/column 它有.
I used to think the db/schema.rb
in a Rails
project stored the database schema, so that ActiveRecord
can know what table/column it has.
但早些时候我惊讶地发现我的项目在删除db/schema.rb
后正常运行!
But earlier I surprisingly noticed that my project runs normally after I delete db/schema.rb
!
那么,既然 Rails
可以在没有它的情况下工作,那么 schema.rb
到底能做什么?
So, since the Rails
can work without it, what does schema.rb
really do?
推荐答案
schema.rb
主要有两个目的:
它记录了数据库模式的最终当前状态.通常,尤其是当您有多个迁移时,很难仅从迁移中推断出模式.有了现有的
schema.rb
,你可以看看那里.ActiveRecord 本身确实不会使用它.它将在运行时内省数据库,因为这比期望用户保持schema.rb
最新更安全.但是,为了避免混淆您的开发人员,您应该始终维护一个与您的迁移保持同步的文件.
It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present
schema.rb
, you can just have a look there. ActiveRecord itself will indeed not use it. It will introspect the database during runtime as this is much safer than to expect users to keep theschema.rb
up-to-date. However to avoid confusion of your developers, you should always maintain a file that is up-to-date with your migrations.
测试使用它来填充数据库架构.因此,rake db:schema:dump
通常作为 rake test:prepare
运行的一部分运行.目的是测试数据库的模式与当前的开发数据库完全匹配.
It is used by the tests to populate the database schema. As such a rake db:schema:dump
is often run as part of the rake test:prepare
run. The purpose is that the schema of the test database exactly matches the current development database.
这篇关于Rails:schema.rb 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!