0

I'm new to rails and stuck on a problem I thought would be pretty straight forward. I would like to upload an image, resize it, and display the resized image. I can upload using carrierwave ok, but when trying to resize it and display it using mini_magick it all goes wrong! Based on the mini_magick docs I created a method in my class to resize the image like this;

class Item < ApplicationRecord

    require "mini_magick"

    mount_uploader :filename, ImageUploader

    def resize_to_dev
        output_file_name = "public/uploads/item/filename/" + "#{self.id}" + "/" + "#{self.id}" + ".jpg"
        image = MiniMagick::Image.open(self.filename.current_path)
        image.resize "100x100"
        image.format "jpg"
        image.write output_file_name
    end

end

This resizes the image and renames it as the itemid.jpg. But if I try to display it using this code in my show template.

<p><% @item.resize_to_dev  %>
<p><% output_file_dir = "public/uploads/item/filename/" + "#{@item.id}" + "/" + "#{@item.id}" + ".jpg"%>
<p><%= image_tag(output_file_dir, alt: 'Image')%>

I get the error;

'The asset "public/uploads/item/filename/2/2.jpg" is not present in the asset pipeline.'

even though the file is in that location.

There must be an easier way to do this! Any assistance is greatly appreciated.

Jinx5269
  • 35
  • 4

1 Answers1

0

I think you don't need to do this converting in your model or view.

You can change your ImageUploader like this:

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{model.id}"
  end

  version :thumb do
    process resize_to_fit: [100, 100]
  end

  # some_other_code
end

And then just call thumb version in your view like this:

<%= image_tag @item.filename.thumb.url, alt: 'Image' %>
mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • Thanks, I did consider that, but I will want to be using more of the mini_magik functionality like adding borders, cropping, etc. So I'd like to display the image created by mini_magik of possible. – Jinx5269 Feb 03 '20 at 00:09
  • It's another question :) – mechnicov Feb 03 '20 at 07:46
  • @Jinx5269 in any case you need to make all `minimagick` manipulations in your uploader, not in view or model. You can read how to make crop [here](https://stackoverflow.com/a/12763720/10608621) or [here](https://stackoverflow.com/a/8930756/10608621). This way you can also make border or round image – mechnicov Feb 03 '20 at 22:27