# Questions about generating customer\_code when creating customer

**URL:** <https://www.ruby-forum.com/t/questions-about-generating-customer-code-when-creating-customer/150841>\
**Category:** Rails\
**Created:** [October 14, 2008, 2:59am UTC](https://www.ruby-forum.com/t/questions-about-generating-customer-code-when-creating-customer/150841 "2008-10-14T02:59:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Titan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/7ba0ec/32.png) [@Titan](https://www.ruby-forum.com/u/Titan)\
**Post date:** [October 14, 2008, 2:59am UTC](https://www.ruby-forum.com/t/questions-about-generating-customer-code-when-creating-customer/150841/1 "2008-10-14T02:59:32Z")

</div>

I am working a MIS which have some customer management work. When the  
customer object is creating, we need to generate a unique code for the  
customer. When in oracle, I created a sequence to solve the problem.  
But now I migrated to mysql, and I tried to use the id created by auto-  
increment. But it fails because it have to call save in after\_save,  
causing a infinite loop. what I want is a unique 6 digit number to  
append to the code,which I use self.id.to\_s in my error code.  
thx in advance for your reply

class Customer \< ActiveRecord::Base  
CTYPES = [  
[‘Person’, ‘P’],  
[‘Corporation’, ‘C’],  
[‘Annual Corp’, ‘A’]  
]  
belongs\_to :nation  
attr\_accessor :code  
def after\_save()  
nation = Nation.find(nation\_id)  
self.code = nation.nation\_code + ctype + Time.now.year.to\_s +  
self.id.to\_s  
self.save  
end

# 

# private

# def get\_ccode

# Customer.find\_by\_sql(“select last\_insert\_id() as code”)[0].code

# end

end
