Reputation: 125
I would like to use @value = SecureRandom.base64(8) to set the password filed when I create a new user only. I don't want it to happened when I edit the user. So my question is where do I use the SecureRandom.base64(8) in the users_controller.rb or the models/user.rb
This is the 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
Upvotes: 4
Views: 671
Reputation: 4802
Use the before_create
callback:
class User < ActiveRecord::Base
before_create :create_password
private
def create_password
self.password = SecureRandom.base64(8)
end
end
Upvotes: 5