Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rails hides the existence of id column?

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).

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.

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?

like image 930
Kirti Thorat Avatar asked Mar 06 '14 16:03

Kirti Thorat


1 Answers

In database design it is generally accepted that numeric id's are preferred, because

  • they are easier to index, and thus easier to "follow" or check when creating links (foreign keys).
  • when editing/updating records, you have a unique (and efficient) identifier

So therefore it is advised to give all tables a unique numeric key, always.

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.

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.

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.

like image 191
nathanvda Avatar answered Sep 19 '22 23:09

nathanvda