2014-10-28 86 views
0

在此处输入代码我正在使用MD5来加密我的密码,但是,在编辑用户配置文件时,用户倾向于不编辑其密码。所以保持原样。但在我的实现中,密码始终更新。如何仅在密码不为空的情况下对密码进行加密

Here is the code in my account model.rb 
    class Admin::Account < ActiveRecord::Base 
     require 'digest/md5' 
     acts_as_reader 
     before_save :encrypt_password 

     def encrypt_password 
     self.password = Digest::MD5.hexdigest(password) 
     end 
    end 

// 编辑 类联系:: AccountsController <的ApplicationController

before_filter :check_login, only: [:new, :index, :edit, :show, :destroy] 
    before_action :set_admin_locale, only: [:new, :index, :edit, :show, :destroy,:create,:update] 
    layout 'admin_layout' 
    # before_action :set_admin_account, only: [:show, :edit, :update, :destroy] 

    # GET /admin/accounts 
    # GET /admin/accounts.json 

    def update_user 
    @admin_account = Admin::Account.find(params[:id]) 
    respond_to do |format| 
    if @admin_account.update(admin_account_params) 
     @success = true 
     session[:nationality] = @admin_account.nationality 
     format.js 
    else 
     @success = false 
     format.js 
    end 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_admin_account 
    @admin_account = Admin::Account.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def admin_account_params 
    gender = "M" 
    if params[:admin_account][:gender] == "Female" 
     gender = "F" 
    end 
    if params[:admin_account][:password] != "" 
     params.require(:admin_account).permit(:email, :password, :name, :account_type, :student_number, :nationality,:photo,:date_of_birth).merge(:gender => gender) 
    else 
     params.require(:admin_account).permit(:email, :name, :account_type, :student_number, :nationality,:photo,:date_of_birth).merge(:gender => gender) 
    end 
    end 

    def register_account 
    gender = "M" 

    if params[:admin_account][:gender] == "Female" 
     gender = "F" 
    end 

    if params[:admin_account][:student_number].present? 
     params.require(:admin_account).permit(:email, :password, :name, :password_confirmation, :student_number,:nationality,:photo,:date_of_birth).merge(:account_type => 'Student', :gender => gender) 
    else 
     params.require(:admin_account).permit(:gender,:email, :password, :name, :password_confirmation,:nationality,:photo,:date_of_birth).merge(:account_type => 'Not Student',:gender => gender) 
    end 
    end 

end 

回答

0

提出一个条件,你encrypt_password方法

def encrypt_password 
    if password.present? and !password.blank? 
    self.password = Digest::MD5.hexdigest(password) 
    end 
end 
+0

对不起,不说明白了。我试过你的实现,如果我的表中的密码列是空的,它会工作。但我希望模型检查用户是否在我的表单上输入了密码,如果他/她没有输入,则绕过加密。 – user3122063 2014-10-28 06:46:17

+0

发布您的accounts_controller也将帮助我理解。 – AshokGK 2014-10-28 07:04:33

+0

我已经使用提供的accounts_controller编辑我的问题 – user3122063 2014-10-28 07:26:52