我正在尝试生成一个随机4-5字母数字字符串来替换标准用户ID,我有一切正常工作,除了每次刷新它生成的页面并替换字符串。我已经尝试过before_save和before_create,但两者似乎都不起作用。
我的模特:
class Admin < ActiveRecord::Base
before_create :admin_ident
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:validatable, :confirmable, :lockable, :timeoutable
validates_uniqueness_of :admin_ident
def admin_ident
self.admin_ident = SecureRandom.hex(2).upcase
end
end
我的设计注册控制器:
class Admin::Admins::RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:admin_admin).permit(:email, :password, :password_confirm, :admin_ident, :f_name, :m_name, :l_name, :dob, :street_number, :street_name, :unit_apt,
:quadrant, :city, :province, :postal_code, :home_tel, :moibile_tel, :office_tel, :office_ext, :company_email,
:position, :start_date, :end_date, :quit, :resigned, :terminated_cause, :terminated_wo_cause, :medical_leave,
:leave_of_abscense, :dl_number, :dl_class, :expiry, :conditions, :sl_number, :sl_certs, :issued, :expires, :emc_1_name,
:emc_1_tel, :emc_1_relationship, :emc_2_name, :emc_2_tel, :emc_2_relationship)
end
def account_update_params
params.require(:admin_admin).permit(:email, :password, :password_confirm, :current_password, :admin_ident, :f_name, :m_name, :l_name, :dob, :street_number, :street_name, :unit_apt,
:quadrant, :city, :province, :postal_code, :home_tel, :moibile_tel, :office_tel, :office_ext, :company_email,
:position, :start_date, :end_date, :quit, :resigned, :terminated_cause, :terminated_wo_cause, :medical_leave,
:leave_of_abscense, :dl_number, :dl_class, :expiry, :conditions, :sl_number, :sl_certs, :issued, :expires, :emc_1_name,
:emc_1_tel, :emc_1_relationship, :emc_2_name, :emc_2_tel, :emc_2_relationship)
end
def set_admin
@admin = Admin.find_by_admin_ident(params[:id])
end
end
My Routes.rb文件:
## Namespace Resources
namespace :admin do
devise_for :admins, controllers: {
:registrations => 'admin/admins/registrations',
:sessions => 'admin/admins/sessions',
:passwords => 'admin/admins/passwords',
:confirmations => 'admin/admins/confirmations',
:unlocks => 'admin/admins/unlocks'
}
resources :admin_static
end
## Devise Scopes
devise_scope :admin do
authenticated do
root to: 'admin/admin_static#home', as: 'admin_authenticated_root'
end
end
不确定我在哪里出错...任何帮助都会很棒!
修改1:
我正在尝试编辑admin / admin_static#主页
答案 0 :(得分:2)
据推测,您正在使用admin_ident
在这些网页上展示some_admin.admin_ident
。
这将更新属性,因为您已将reader方法替换为设置admin ident的方法。我建议您调用该方法set_admin_ident
(并更新before_create
以匹配)
答案 1 :(得分:1)
我认为你可能会使用相同的名称来进行字段和随机更新字段的方法。
before_create :generate_admin_ident
validates_uniqueness_of :generate_admin_ident
def generate_admin_ident
begin
self.admin_ident = SecureRandom.hex(2).upcase
other_admin = Admin.find_by(admin_ident: self.admin_ident)
end while other_admin
end
这应该使admin_ident
的所有用法都引用该字段而不是随机生成器。
请注意,您还使用验证来确保唯一性,但这会导致create!
或save
的任意调用失败。这些应该包含在begin..rescue..retry块中,或者随机生成器应该自己验证唯一性。
begin..end while
循环和other_admin
代码旨在手动验证方法生成的admin_ident
的唯一性,并继续尝试,直到找到唯一值。