我有一个名为 user 的设计模型。当用户注册时,他们将被引导填写名为“userinfo”的表单。我有一个名为 userinfo 的模型。一旦创建了新的 userinfo,我就会给每个 userinfo 一个唯一的令牌。我允许在我的 userinfo 控制器中使用“令牌”。它有效,但每次我编辑表单和更新时,唯一的标记也会改变。我想我应该只在 userinfo#show 页面上显示第一个创建的令牌。但是,如果用户更新他们的 userinfo 表单 5 次,将创建 5 个令牌并浪费 4 个。
所以实际问题:当 userinfo#new 发生时创建唯一的令牌并将其显示在 userinfo#show 页面上。当 userinfo#edit 和 userinfo#update 发生时,不应更新唯一令牌。
我的用户信息模型:
class Userinfo < ActiveRecord::Base
belongs_to :user
before_save :set_token
def set_token
self.token = rand(100000..999999)
end
end
用户信息控制器:
class UserinfosController < ApplicationController
before_action :find_userinfo, only: [:show, :edit, :update, :destroy, :log_impression]
before_action :authenticate_user!
def index
@userinfors = Userinfo.search(params[:search])
end
def show
end
def new
@userinformation = current_user.build_userinfo
end
def create
@userinformation = current_user.build_userinfo(userinfo_params)
if @userinformation.save
redirect_to userinfo_path(@userinformation)
else
render 'new'
end
end
def edit
end
def update
if @userinformation.update(userinfo_params)
redirect_to userinfo_path(@userinformation)
else
render 'edit'
end
end
def destroy
@userinformation.destroy
redirect_to root_path
end
private
def userinfo_params
params.require(:userinfo).permit(:name, :email, :college, :gpa, :major, :token, :skills, :user_img)
end
def find_userinfo
@userinformation = Userinfo.friendly.find(params[:id])
end
end
看法:
<%= @userinformation.token %>
尝试这样的事情:
def set_token
self.token ||= rand(100000..999999)
end
该||=
说,“设置token
一个随机数,除非token
已经有值”(大致)。
顺便说一句,为了回应下面的评论和您原来的问题,确实使用:
rand(100000..999999)
不是个好主意。发现了两个问题:
如评论中所述,如果您不介意 UUID 的格式,则使用 SecureRandom.uuid 是一件好事:
ad9ed387-ec8e-4091-84b1-fe2ce2bbfcd4
在这种情况下,您会执行以下操作:
def set_token
self.token ||= SecureRandom.uuid
end
顺便说一下,这就是我在代码中所做的。
使用 SecureRandom.uuid,您生成重复令牌的可能性非常小。但是,如果您担心这种非常小的机会,您还可以在数据库级别和模型中强制执行唯一性。如果您对答案感兴趣,这些是您可能想要发布的单独问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句