【发布时间】:2017-12-03 17:32:06
【问题描述】:
我有一个名为 user 的设计模型。当用户注册时,他们将被引导填写名为“userinfo”的表格。我有一个名为 userinfo 的模型。一旦创建了新的用户信息,我就会给每个用户信息一个唯一的令牌。我在我的用户信息控制器中允许“令牌”。它有效,但每次我编辑表单并更新时,唯一令牌也会发生变化。我在想我应该只在 userinfo#show 页面上显示第一个创建的令牌。但是如果一个用户更新他们的用户信息表单 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 %>
【问题讨论】:
-
顺便说一句,您的“唯一”令牌可能只是唯一的。
-
我知道,我怎样才能让它独一无二?
-
如果您不介意令牌是字符串,请使用 SecureRandom.uuid。
-
或
SecureRandom.random_number*10000000000000000:)
标签: ruby-on-rails ruby