Rails 6 + Active Storage : set a default image that can have a variant

Viewed 1545

I need to set a default image for active storage attachments, in case of no image was uploaded.

I could make a simple helper calling an image from /assets/images but in this case, those images won't work with variants (e.g. <%= image_tag image.variant(resize_to_fill: [50,50]) %>)

Browsing the web, I found this interesting article that gives some clues : https://gorails.com/forum/how-do-i-set-and-use-a-default-image-with-active-storage, but it is not enough for my case.

Attaching the image with a before_create callback sounds overkill to me, as it is going to upload the same image several times to the storage.

  • Is there a way to set a default picture that is going to behave like any Active Storage attachment, and accepts variants ?
  • Is there a way to make minimagick variants working with "normal" images from assets path ?
1 Answers

Create a Method to fetch image . Follow the below snippet:

  def fetch_cover_image
    if self.cover_image.attached?
      Rails.application.routes.url_helpers.rails_blob_url(self.cover_image, 
       host: Rails.application.credentials[Rails.env.to_sym][:host])
    else
      ActionController::Base.helpers.image_url('cover_image.jpg')
    end
  end
Related