带有 sqlite3 的 rails5 中 id 模型的 lambda uuid 生成器

lambda uuid generator for id's model in rails5 with sqlite3

由于sqlite3中没有uuid处理,我尝试自己生成。

许多其他帖子让我想到了这个:

create_table :users, id: false do |t|
  t.string :id, :primary_key => true, null: false, default: -> { "(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))" }
  ...
end

当您执行 User.create ....
时,它实际上会在 id 字段中生成默认的随机 uuid 但是当你做 User.new 时,这实际上是我在控制器中的情况(通过默认生成的视图)我推送 New User link 我有:

所以我想知道是否有一种方法可以在通过 new 创建 id 字段时生成默认值,例如 SecureRandom 或类似的东西.

呃,解决方法其实很简单:

在我的 app/models/application_record.rb:

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  after_initialize :generate_uuid

  protected
  def generate_uuid
    self.id = SecureRandom.uuid unless self.id
  end
end

可能遇到同样情况的人:

  • 我显然没有保留 id 字段 (t.string :id, default: -> { "(lower..."}) 的默认值定义。
  • 我把id默认集合的类型改成了:stringcreate_table :users, id: :string do |t|)。