Rails 3.1中的Autoincrement文本字段

我是铁杆新手,我希望你能帮助我。 我正在创建一个管理我的仓库的应用程序。 在我的传输文档部分中,我需要一个不可编辑的字段,为任何文档分配ID,我希望此ID自动增加。

ID由前缀(根据登录的用户而更改)和每次用户创建传输文档时必须递增的整数组成。 一个例子可以更好地解释它:

1)用户“Mark”登录应用程序

First Transport Document ID: MARK00001 Second Transport Document ID: MARK00002 

1)用户“Peter”登录申请

 First Transport Document ID: PETE00001 Second Transport Document ID: PETE00002 

等等。 有关如何做到这一点的任何建议?

您可以挂钩记录上的before_create回调:

 class TransportDocument << ActiveRecord::Base before_create :set_friendly_id private def set_friendly_id # create your friendly_id here (hard to sample code without knowing your model) # friendly_id = current_user.name.upcase + number_of_records_plus_one_nice_format self.friendly_id = friendly_id end end 

如果您需要帮助组装friendly_name,我们需要了解有关您的模型结构的更多信息。

首先,我会在before_createfilter中获得最高值,然后生成一个新数字。 User模型应该具有类似于前缀方法的方法来获取用户前缀。 假设TransportDocument属于用户,我会做这样的事情:

 class TransportDocument << ActiveRecord::Base before_create :set_per_user_id def document_id_txt "#{user.prefix}#{document_id}" end private def set_per_user_id val = user.transport_documents.maximum(:document_id) self.document_id = val + 1 end end 

我没有测试代码,但它应该粗略地工作。 如果您需要在字段中存储前缀,则返回实际最高值会稍微繁琐一些。

在document_id字段上设置一些validation以确保每个用户的唯一性也是一个好主意。