Updating `User` attributes without requiring password

前端 未结 9 1645
醉酒成梦
醉酒成梦 2021-01-30 17:27

Right now, users can edit some their attributes without having to enter their password because my validations are set up like this:

validates :password, :prese         


        
9条回答
  •  孤街浪徒
    2021-01-30 18:28

    # It smells
    
    def update
      if params[:user][:password].blank?
        params[:user].delete :password
        params[:user].delete :password_confirmation
      end
    
      if @user.update_attributes(params[:user])
        flash[:success] = "Edit Successful."
        redirect_to @user
      else
        @title = "Edit user"
        render 'edit'
      end
    end
    
    # Refactoring
    
    class User < ActiveRecord::Base
      ...
      def update_attributes(params)
        if params[:password].blank?
          params.delete :password
          params.delete :password_confirmation
          super params
        end
      end
      ...
    end
    
    def update
      if @user.update_attributes(params[:user])
        flash[:success] = "Edit Successful."
        redirect_to @user
      else
        @title = "Edit user"
        render 'edit'
      end
    end
    
    # And little better
    
    class User < ActiveRecord::Base
      ...
      def custom_update_attributes(params)
        if params[:password].blank?
          params.delete :password
          params.delete :password_confirmation
          update_attributes params
        end
      end
      ...
    end
    
    def update
      if @user.custom_update_attributes(params[:user])
        flash[:success] = "Edit Successful."
        redirect_to @user
      else
        @title = "Edit user"
        render 'edit'
      end
    end
    

提交回复
热议问题