i have a database table with this column t.integer :account_number, :limit => 9. I need this column to automatic generate on the account creation, to auto-increment by 50 for each account created and it has to start( from the first account) at value of 450230000. So i will have the account with ID = 1 and ACCOUNT_NUMBER = 450230000, account with ID = 2 and ACCOUNT_NUMBER = 450230050.
I'm using Rails 4.2.5 and SQLite as database. There is a way to have this type of auto-increment column in Rails?
            Asked
            
        
        
            Active
            
        
            Viewed 278 times
        
    0
            
            
        
        Luigi Versitelli
        
- 41
 - 8
 
- 
                    [this](http://stackoverflow.com/questions/692856/set-start-value-for-autoincrement-in-sqlite) seems relevant – Imran Ali Jun 06 '16 at 10:04
 - 
                    Right, i just have to create the first row on my own then delete it when the count will start, thanks! – Luigi Versitelli Jun 06 '16 at 10:13
 
2 Answers
2
            Add callback in model before saving your object
before_create :set_account_number
def set_account_number
  last_account_number = Account.maximum(:account_number)
  self.account_number = last_account_number.to_i + 50
end
Do something like that in your model
        Sachin R
        
- 11,606
 - 10
 - 35
 - 40
 
- 
                    Ok, it works but i need that, by default, on the first account i will create the account number has to be 450230000. It is possible? – Luigi Versitelli Jun 06 '16 at 10:07
 - 
                    
 
1
            
            
        This logic, can help you
before_create :inc_acc_num   //callback 
def inc_acc_num
  self.account_number = Account.last.try(:account_number) + 50
end
        Mukesh
        
- 921
 - 10
 - 23