管理员帐户会创建一个用户帐户,这会自动生成由用户的姓氏和姓氏确定的用户名。 一旦创建了用户名,我希望用户只能更新一次 - 注意:这可以是在任何时间或多次登录后,但一旦用户名被更改,一旦需要进行更新。
使用Rails和simple_form。编辑表格如下。
= simple_form_for(current_user) do |f|
= f.error_notification
.form-inputs
= f.input :name, required: true, label: 'Name'
= f.input :username, required: true
= f.input :email, required: true
= f.input :password, required: true, placeholder: ("#{@minimum_password_length} characters minimum" if @minimum_password_length)
= f.input :password_confirmation, required: true
.form-actions
= f.button :submit, "Update Profile", class: 'btn btn-primary btn-block btn-lg'
管理员/用户控制器。
def create
@user = User.new(user_params)
@user.password = SecureRandom.base64()
nameArray = @user.name.split(' ')
@user.username = nameArray[0][0].downcase + nameArray[-1][0..6].downcase
respond_to do |format|
if @user.save
@user.send_reset_password_instructions
format.html do
redirect_to [:admin, @user],
notice: "#{@user} was successfully created. A confirmation email was sent to: #{@user.email}"
end
else
format.html do
flash[:alert] = "User #{@user} already exists, or you have not filled in all of the required fields."
render :new
end
end
end
end
提前致谢。
答案 0 :(得分:1)
向用户添加新列,如:已编辑
def change
add_column :users, :eited, :boolean, default: false
end
在您的模型中,用户添加calback after_update
class User < ApplicationRecord
after_update :set_edited!
before_update :check_if_edited!
def is_edited?
edited?
end
private
def check_if_edited!
# there you can set the error message or what you want
errors.add(:base, :invalid, message: "Your message")) if edited?
end
def set_edited!
transaction do
self.edited = true
self.save!
end
end
end
在用户控制器中添加限制以更新用户(如果是is_edited?
)def update
if current_user.is_edited?
// preform action
end
end
P.S。迁移逻辑以将属性分配给模型用户
class User < ApplicationRecord
after_create :assign_attributes
private
def assign_attributes
transaction do
self.password = SecureRandom.base64()
name_array = name.split(' ')
self.username = nameArray[0][0].downcase + nameArray[-1][0..6].downcase
self.save!
end
end
end
答案 1 :(得分:0)
据我所知,最好的方法是在用户模型中使用call_back:
before_update{|user|
user.write_user_name_changed unless user.created_at == user.updated_at
}
def write_user_name_changed
self.user_name_changed = params[:username]
true
end