How to create a special order_number that is based off the table id column in PostgreSQL and Rails -


i have orders table in sql database (postgresql if matters, , rails 4.04) , want column "number" in orders table kind of shadow id column. in other words want automatic sequential field want in form:

order::product_nu_prefix + ((order::starting_product_no + order.id).to_s) 

so if set

product_nu_prefix = 'pe' ,  starting_product_no = '11681' 

then first order create have product number:

kb11682 ,  kb11683 

should purely in postgresql or there way in rails? keep in mind i'll need know latest order.id when order comes in because when save new record want field saved correctly.

you're looking @ uuid's (universally unique identifiers)

these allow assign special id record, giving instant reference throughout app. such use cases include likes of order numbers, api keys , message id's

we implement you're asking quite regularly:

#app/models/order.rb class order < activerecord::base     before_create :set_num      private     def set_num         unless self.num             loop                 token =  securerandom.hex(10)                 break token unless self.class.exists?(num: token)             end         end     end  end  orders id | num | other | attrs | created_at | updated_at 

rails has series of built-in uuid-generators:

securerandom.uuid #=> "1ca71cd6-08c4-4855-9381-2f41aeffe59c" securerandom.hex(10) # => "52750b30ffbc7de3b362" securerandom.base64(10) # => "ecmtpzwwraozda==" 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -