I have a model Token, which has a field token_number that I need to auto increment (starting from 1001), if and only if the user does not provide it. The problem is that, since the user has the option to provide this field, I can’t exactly query the database and ask for the largest token_number. I found one answer on this forum, but I’m quite certain there has to be a better way to do it than to execute an SQL statement? Auto increment a non-primary key field in Ruby on Rails
Share
Interesting question for me. Unfortunately, rails doesn’t provide a way to auto-increment columns, so we must resort to SQL with little automation. I tried this in Rails 3.0.7 using PostgreSQL as my database and it works and hope this will be useful:
Creating sequence for token_number PGSql Documentation
Now, since there is a possibility of token_number being set by the user manually, we’ll need to generate the token_number only if it is not being set. Read about Callbacks here. With that we have,
A sample run. Please note that for the first token I am not setting token_number and it generates the token_number sequence and for the second I am assigning.