我在rails应用程序中有一个模型Document
。它具有列name
和key
。
在我的create
操作控制器中,我从前端获取文档名称,并使用key
为securerandom
动态设置一个值。
我在这种情况下的实现是:
class Document < ApplicationRecord
belongs_to :user
validates :key, presence: true, uniqueness: true
end
class DocumentsController < ApplicationController
def create
current_user.documents.create(create_document_params)
redirect_to '/'
end
private
def create_document_params
params.require(:document).permit(:name).merge(key: "#{SecureRandom.hex(6)}#{Time.now.to_i}")
end
end
这种方法的问题在于,动态键逻辑位于控制器中,我认为它应该是文档模型的一部分。
为此,我尝试在Active Record Callbacks
模型中使用Document
使用before_create
。我将securerandom密钥逻辑移动到Document模型,如下所示:
class Document < ApplicationRecord
belongs_to :user
validates :key, presence: true, uniqueness: true
before_create do
self.key = "#{SecureRandom.hex(6)}#{Time.now.to_i}"
end
end
但是现在我的问题是,每当我调用create
或new
时,key
的值始终相同。但是它应该在每次create
调用之前随机生成。
我做错了什么?
class DocumentsController < ApplicationController
def create
@document = current_user.documents.new(create_document_params) do |doc|
# you could also use SecureRandom.uuid
doc.key = "#{SecureRandom.hex(6)}#{Time.now.to_i}"
end
# Don't make the stupid assumption that the user input always will be valid!
if @document.save
redirect_to root_path, notice: 'Document created'
else
render :new
end
end
private
def create_document_params
params.require(:document)
.permit(:name)
end
end