开发者

Does ActiveRecord assign a key to every table using the naming convention "ID", and if so, why?

My understanding is that Actice Record is based on a object-relational mapping (ORM) pattern described by Martin Fowler in his book Pattern of Enterprise Application Architecture (Addison-Wesley, 2002); which states a one-to-one mapping relationship exists between a database record and the object that represents it in an object-oriented program (OOP). When Rails creator David Heinemeier sought to implement an ORM for his Rails framewo开发者_运维问答rk, he based it on Fowler's pattern.

Here's the problem, does ActiveRecord assign a surrogate primary key to every table using the naming convention "ID", and if so, why? Reason I ask is that it appears it'd make more sense to assign a a surrogate primary key using the naming convention "tablename_ID"; as in fact it appears ActiveRecord does when creating foreign keys. Further, is it possible to override the default config, and assign a surrogate primary key using the naming convention "tablename_ID"; reason being that especially in the case of primary keys, it appears to be a good idea not to use a shared name, since telling the difference between two columns ID's is not possible if simply looking at the column namesing: ID, ID, ID. As a use case example of where this appears there would be a problem, if I export data to a single table from two tables, there will be two columns with the ID name; when I import that document with updates, it would appear that there's no way to map the ID columns by default.


It's already obvious to see what the ID is, because it is in a certain table. You don't have table_name.table_name_id but table_name.id. I like the distinction between foreign keys and primary keys this way, but admittedly, it's a matter of opinion.

Unless you have a really good reason to use anything other, you should stick to the convention. That's what conventions are for. ActiveRecord gives you the option to change it, like so:

ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore

This sets the way primary keys are generated globally. products.id becomes products.product_id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜