开发者

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

开发者 https://www.devze.com 2023-02-22 06:37 出处:网络
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 rath

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 unt开发者_运维技巧il 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!


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
0

精彩评论

暂无评论...
验证码 换一张
取 消