In Rails how would one generate a unique serial number for a new instance of a model?

怎甘沉沦 提交于 2019-12-05 04:29:06

问题


In Rails, I'm looking for a way to generate an auto-incrementing serial number for internal record keeping for new instances of a model. I would like to avoid creating database specific code and rather have a solution that will work regardless of the database. My current idea is to wait until the model is saved and then grab the ID of the saved model and use that as a suffix of the serial number, but then I would have to save each record twice on creation.

Any ideas?

Thanks for looking!


回答1:


I would recommend constructing the serial model in the model instead. This will give you more flexibility to adjust the serial number format later, and it will keep the unique auto-increment in the database instead. Use a regular auto-increment integer primary key and then create the serial number like this:

class Product
  def serial_number
    "PLN-%.6d" % id
  end
end

So if you have a product with id = 567 for example, you'll have a serial number like this:

Product.find(567).serial_number
=> PLN-000567


来源:https://stackoverflow.com/questions/5569391/in-rails-how-would-one-generate-a-unique-serial-number-for-a-new-instance-of-a-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!