为什么 Rails 隐藏了 id 列的存在? [英] Why Rails hides the existence of id column?
问题描述
我不太明白需要在 Rails 中隐藏 id
列的存在.它既不会反映在 migration
文件中,也不会反映在 schema.rb
文件中.新手无法知道名为 id
的列已被默认创建为 primary key
的事实.除非他们去检查数据库中表的实际模式(rails dbconsole
).
I don't quite understand the need to hide the existence of id
column in Rails.
It is neither reflected in migration
file nor the schema.rb
file.
There is no way for a newbie to know for the fact that a column named id
has been created by default as a primary key
.
Unless they go and check the actual schema of the table in database (rails dbconsole
).
我可以看到迁移文件中默认包含的 timestamps
宏以及 schema.rb
中的两个字段 created_at
和 <代码>updated_at.在这里,开发人员至少得到了一个线索.Rails 也可以为 id
列做同样的事情.但事实并非如此.
I can see the timestamps
macro included by default in the migration file as well as in schema.rb
as two fields created_at
and updated_at
. Here, a developer at least gets a clue. Rails could have done the same for id
column too. But it doesn't.
为什么要对 id
列保密?它是著名的convention over configuration
的一部分吗?还是所有 MVC 框架的规范?
Why the secrecy around id
column? Is it a part of the famous convention over configuration
? Or is it a norm across all MVC frameworks?
推荐答案
在数据库设计中,人们普遍认为数字 id 是首选,因为
In database design it is generally accepted that numeric id's are preferred, because
- 它们更容易索引,因此在创建链接(外键)时更容易关注"或检查.
- 在编辑/更新记录时,您有一个唯一(且有效)的标识符
因此,建议始终为所有表格提供唯一的数字键.
So therefore it is advised to give all tables a unique numeric key, always.
现在这个数字键对您的应用程序没有任何意义,它是您的数据库层的实现细节".还要确保每个表都有一个 ID,除非您明确要求不要这样做.
Now this numeric key has no meaning whatsoever to your application, it is a "implementation detail" of your database layer. Also to make sure every table has an id, unless you explicitly ask not to.
我认为这确实属于约定优于配置"的说法:如果每个表都应该有一个 id,为什么还要为每个表明确指定一个 id.
I think this would indeed fall under the "convention over configuration" nomer: why explicitly specify an id for each table if you each table should have one.
时间戳不同:这对某些表很有趣,但对于相同的表,它根本不重要.这也取决于您的应用程序.
The timestamps is different: this is interesting for some tables, but for same tables it is not important at all. It also depends on your application.
请注意,这与 MVC 完全无关.MVC 中的 M 是数据的容器,但在 MVC 中,模型如何填充实际上并不重要.换句话说:ORM 部分不是 MVC 的一部分.您会看到在大多数 MVC 实现中没有 ORM,或者绝对不像与 Rails 那样紧密集成.
Note that this is not at all related to MVC. The M in MVC is a container for data, but in MVC it is actually not really important how the Model gets filled. In other words: the ORM part is not part of MVC. You will see that in most MVC implementations there is no ORM, or definitely not as tightly integrated as with Rails.
简而言之:恕我直言,从迁移中省略id"并不是什么秘密,它只是为了让生活更轻松,为您节省更多的输入时间,并且它确保您遵循一个好的除非您明确不想想要,否则约定俗成.
So in short: imho ommitting the 'id' from the migration is not a secret, it is just to make life easier, saves you some more typing, and it makes sure you follow a good convention unless you explicitly do not want to.
这篇关于为什么 Rails 隐藏了 id 列的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!