views:

167

answers:

2

I am building my first rails application and I expect it to eventually have many models/controllers. And of course they each have an ID associated with them. I can see that they are starting to get confusion already.

In the users controller the field is called id, but in every other controller i label it as user_id. When a controller is manipulating multiple models or calling actions in other controllers, it seems tedious to keep all the ids straight.

I would like to just prefix them all to be explicit, but am afraid this might cause errors down the road as user does not actually have a user_id field. This would be an issue when using something like update_attributes!.

Has anyone else experience this problem? Is it really a problem or am I making this into a bigger issue than it actually is? Are there any standard best practices for naming the id field?

Thanks! Dave

+7  A: 

This is really not a problem. The convention in Rails is to label the primary key of the table as id, and any foreign keys that access that table as table_name_id.

I'd advise against changing this default behaviour as Rails is more about convention over configuration, and this method of naming does actually make your DB schema far easier to understand as complexity grows.

If you do decide to change the primary key name, there is also the chance that you will run into further problems when using other peoples gems and plugins.

Mr. Matt
+1  A: 

As far as I know the best name for id field is id.

I have application with about 30 models and almost the same number of controllers. I manipulate many models in single controller and I didn't ever have any problem with id. Maybe we could help you a little more if you paste some code.

klew