用于带有sqlite3

时间:2017-03-22 10:51:33

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

由于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

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

  • 在我的表单中id值:new_user_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)))
  • 即使我将表单选项更正为form_for @user, html: {id: "new_user"},当我提交表单时,我会被重定向到http://localhost:3000/accounts/lower(hex(randomblob(4)))%20%7C%7C%20'-'%20%7C%7C%20lower(hex(randomblob(2)))%20%7C%7C%20'-4'%20%7C%7C%20substr(lower(hex(randomblob(2))),2)%20%7C%7C%20'-'%20%7C%7C%20substr('89ab',abs(random())%20%25%204%20+%201,%201)%20%7C%7C%20substr(lower(hex(randomblob(2))),2)%20%7C%7C%20'-'%20%7C%7C%20lower(hex(randomblob(6)))
    这似乎也是id字段User.new的价值。

所以我想知道是否有一种方法可以通过id创建new字段的默认值,就像SecureRandom或类似内容一样。< / p>

1 个答案:

答案 0 :(得分:2)

Erf,解决方案实际上非常简单:

在我的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|)。