I have a rails application linked to a database table, which contains e-mail addresses and passwords. I would like to create a unique number which will identify each of the users in the system. This number will be given to a user upon registration, and stored in the field user_id on the same table.
So, for example, john@foo.bar could get 0001 as an ID, martha@foo.bar could get 0002, and so on.
My question is: what is the best way to do this?
Should I seed the database (rake db:seed) with the first user_id (0001) and write a method in the controller to +1 the user_id every time? If that is the case, how can I access the last row in order to find out the last user_id?
An alternative way would be to find the largest user_id in the table and +1 it. For that I guess I need to use tablename.find_by_user_id or something similar (would tablename.find_by_user_id.max work?)
A third way would be to store the latest user_id somewhere, and have the application retrive it when needed. Where could this information be stored?
I’m very new to rails . Would appreciate your feedback about which is the best way to go.
Thanks,
TimmyOnRails
Lets assume your model has two attributes name and email. Now by default rails will generate three more columns for you
1 id – auto incremental
2 created_at and updated_at – timestamps
Rake db:seed is one of the good solution in case you want to prepopulate the database. All you need to worry about is name and email. Add proper validations for these attributes. Rest rails will handle ie id is maintained by rails itself. You don’t need to worry about it. Created_at and updated_at columns are also maintained by rails.
If you new to rails then I will suggest you to check http://railsforzombies.com and that will you a good idea about active records
Railsguides and RailsCasts are also two other learning materials for rails.