Skip to content

Validation before processing #2791

@SaimonL

Description

@SaimonL

What

I get CarrierWave::ProcessingError error in the controller when creating or updating a model that uses CarrierWave uploader.

How

Just rename a text file from "test.txt" to "test.png" and upload it.
The uploader class CookingIngredientPictureUploader < CarrierWave::Uploader::Base is expecting an image.

Why

CarrierWave is running this code first which resizes the images

version :small do
  process resize_to_fit: [128, 128]
end

Solution

The code must run check on extension_allowlist and content_type_allowlist first before processing anything.

I have specified these both in my uploader but they are not checked before the "version" is executed.

def content_type_allowlist
  %w[
    image/jpeg
    image/jpg
    image/png
    image/gif
  ]
end

def extension_allowlist
  %w[jpg jpeg gif png]
end

Temporary Workaround

In my controller I have to use rescue which I am not found of.

def update
  if @cooking_stage_ingredient.update(cooking_stage_ingredient_params)
    redirect_to @cooking_recipe, notice: 'Cooking stage ingredient was successfully updated.', status: :see_other
  else
    render :edit, status: :unprocessable_content
  end
rescue CarrierWave::ProcessingError
  @cooking_stage_ingredient.errors.add(:picture, 'Only JPG, PNG, and GIF are allowed.')
  render :edit, status: :unprocessable_content
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions