由于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>
答案 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
集的类型更改为:string
(create_table :users, id: :string do |t|
)。