在Rails中,如何为模型的新实例生成唯一的序列号? [英] In Rails how would one generate a unique serial number for a new instance of a model?

查看:84
本文介绍了在Rails中,如何为模型的新实例生成唯一的序列号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails中,我正在寻找一种为模型的新实例生成用于内部记录保存的自动递增序列号的方法.我想避免创建特定于数据库的代码,而希望有一个可以在任何数据库下工作的解决方案.我当前的想法是等到保存模型后再获取已保存模型的ID并将其用作序列号的后缀,但随后我将不得不在创建时将每条记录保存两次.

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.

有什么想法吗?

感谢您的光临!

推荐答案

我建议改为在模型中构造串行模型.这将使您在以后调整序列号格式时具有更大的灵活性,并且将唯一的自动增量保留在数据库中.使用常规的自动递增整数主键,然后按如下所示创建序列号:

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

因此,例如,如果您有一个ID = 567的产品,那么您将拥有一个像这样的序列号:

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

这篇关于在Rails中,如何为模型的新实例生成唯一的序列号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆