【问题标题】:generate UUID on object creation in rails在 Rails 中创建对象时生成 UUID
【发布时间】:2019-06-20 23:21:51
【问题描述】:

我想在创建新对象时生成唯一 ID

我有一个名为 Product 的模型,它有名称、重量和价格。我想创建一个以“TPK”+随机 8 个字符开头的唯一 ID 并将其添加到产品表中。有什么简单的方法可以实现?

这是当前的迁移文件

class Products < ActiveRecord::Migration[5.2]
 def change
  create_table :products do |t|
  t.string :weight
  t.string :product_name
  t.integer :price
  .......

我想向它添加另一个名为 product_code 的属性,并且我希望它在创建时具有唯一的 ID,以 "TPK" + random 8 字符开头

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    我建议仅使用迁移来更新架构并将模型逻辑保留在模型中。因此,首先,您创建一个迁移以将 product_code 添加到 products 表中。然后在 Product 模型中添加一个钩子来创建一个默认代码:

    class Product < ApplicationRecord
      before_create :default_product_code
    
      private
      def default_product_code
        #your implementation
        #e.g. self.product_code = 'TPK' + SecureRandom.hex(4)
      end
    end
    

    【讨论】:

    • 您还应该在分配之前检查新生成的代码是否唯一(并在该列上具有唯一索引)。但这个答案是精神
    • @CodyCaughlan 是的,你是对的。我专注于方法而忽略了实现,这需要考虑更多细节,例如唯一性。
    猜你喜欢
    • 2013-02-16
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 2016-10-27
    • 2015-10-05
    相关资源
    最近更新 更多