我想在创建新用户时使用@value = SecureRandom.base64(8)设置密码字段。当我编辑用户时,我不希望它发生。所以我的问题是我在哪里使用users_controller.rb中的SecureRandom.base64(8)或者models / user.rb
这是users_controller.rb
def create
if user.save
user.send_invitation
redirect_to root_url, notice: "Signed up!"
else
render :new
end
end
def destroy
@user = User.find(params[:id])
if @user.destroy
redirect_to root_url, notice: "User was deleted successfully!"
end
end
def edit
respond_with(user)
end
def update
@user.password_confirmation = User.value
params[:user].delete(:password) if params[:user][:password].blank?
params[:user].delete(:password_confirmation) if params[:user][:password_confirmation].blank?
if user.save
redirect_to users_path, :notice => "Saved your updates!"
else
render :edit
end
end
答案 0 :(得分:4)
使用before_create
回调:
class User < ActiveRecord::Base
before_create :create_password
private
def create_password
self.password = SecureRandom.base64(8)
end
end