为什么Rails隐藏id列的存在? [英] Why Rails hides the existence of id column?
问题描述
我不太了解是否需要在Rails中隐藏 id
列的存在。
它既没有反映在 migration
文件中,也没有反映在 schema.rb
文件中。
对于新手来说,由于默认情况下已创建名为 id
的列作为主键
。
除非他们去检查数据库中表的实际架构( 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
).
我可以看到默认情况下,迁移文件以及 schema.rb
中包含的 timestamps
宏是两个字段, code> 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
列保密?它是否是著名的约定上的配置
的一部分?还是在所有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.
我认为这确实属于常规配置之上的范畴:为什么要明确指定
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屋!