I am trying to resize my images before uploading them with Rails' ActiveStorage. The following controller action works like a charm:
class CatsController < ApplicationController
require 'mini_magick'
def create
@cat = current_user.cats.new(cat_params)
params[:cat][:images].each do |image|
mini_image = MiniMagick::Image.new(image.tempfile.path)
mini_image.resize '1200x1200'
end
if @cat.save
...
end
end
end
But I would like to keep my controllers skinny and move this functionality to the model. But when I do so, Rails can't find tempfile
in the model.
Is there no way at all to access tempfile
in the model?
Thanks for any help.
Alternatively you can create a service
# app/services/image_resizer.rb
class ImageResizer
def self.call(images, size)
Array(images).each do |image|
i = MiniMagick::Image.new(image.tempfile.path)
i.resize size
end
end
end
def create
@cat = current_user.cats.new(cat_params)
ImageResizer.call(params[:cat][:images], '1200x1200')
if @cat.save
...
end
end