我正在尝试使用vidibus-uuid生成与我的域模型关联的UUID。这意味着每次创建新域时,也会创建随机生成的UUID。目前,我正在使用带有Rails的Mongoid并具有以下域模型:
class Domain
include Mongoid::Document
include Vidibus::Uuid::Mongoid
field :name, type: String
field :url, type: String
field :domain_uuid
validates :domain_uuid, :uuid => {:allow_blank => true}
belongs_to :user
end
My Domain Controller在创建新域时看起来像这样:
def create
@domain = Domain.new(params.require(:domain).permit(:name, :url, :domain_uuid))
if @domain.save
flash[:notice] = "Domain was saved succesfully."
redirect_to @domain
else
flash[:error] = "There was an error saving the domain. Please try again."
render :new
end
end
在我看来,我有以下内容:
<%= form_for @domain do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter domain name" %>
</div>
<div class="form-group">
<%= f.label :url %>
<%= f.text_field :url, class: 'form-control', placeholder: "Enter domain url" %>
</div>
<div class="form-group">
<%= f.label :domain_uuid %>
<%= f.text_field :domain_uuid, class: 'form-control', placeholder: "Enter domain url" %>
</div>
<div class="form-group">
<%= f.submit "Save", class: 'btn btn-success' %>
</div>
<% end %>
是否有类似f.text_field:domain_uuid.RandomGenerate()的东西来随机生成UUID?我知道我在视图上的实现是不正确的...只需要一些关于如何获取随机生成的UUID的指南。
谢谢你们
答案 0 :(得分:2)
我使用uuidtools
gem 'uuidtools'
生成UUID的简单方法,它看起来不错:
UUIDTools::UUID.random_create.to_s
# "7b1fdc50-084c-4c20-a0b2-d76c060ed9cd"
为您的属性提供更好的名称&#39; uuid&#39;,但不是&#39; domain_uuid&#39;,您已经在域中。
class Domain
include Mongoid::Document
field :name, type: String
field :url, type: String
field :uuid
validates :uuid, :presence => true
belongs_to :user
before_create do
set_uuid if uuid.blank?
end
private
def set_uuid
self.uuid = UUIDTools::UUID.random_create.to_s
end
end