I had a problem checking if this parameter is empty or not on rubies on rails

I am trying to check if User_avatar is present or not in the form (submitted by the user). If he selects another image for updating, I need to switch to cropping, otherwise it will be redirected to edit the page.

But if I run the following code on the controller, it will be redirected directly to the page editing, if I also select and send the image.

controller

if @user.update(user_params)

     if((@user.user_avatar.present?) && (!params[:user_avatar].blank?) )
       format.html { render :action => 'crop'}

     else

       format.html { redirect_to edit_user_path, notice: 'user was successfully updated.' }

      format.json { head :no_content }

    end

else

   format.html { render action: 'edit' }

   format.json { render json: @user.errors, status: :unprocessable_entity }

end

def user_params
params.require(:user).permit(:user, :crop_x, :crop_y, :crop_w, :crop_h,  :user_avatar, :fname, :lname,  :city_id, :location_id, :email, :password, :course, :phone_no)
end
+4
source share
1 answer

In rails, you can use a method has_key?that returns trueor false, rewriting above, if the condition

if @user.user_avatar.present? and params[:user].has_key?(:user_avatar)
  # your code
end
+1
source

Source: https://habr.com/ru/post/1530377/


All Articles