So in my Rails app I have this ActiveRecord model:
# app/models/user.rb
class User < ApplicationRecord
include UserAvatarUploader::Attachment(:avatar)
before_save :save_avatar_derivatives, if: Proc.new{|x| x.avatar_changed? && x.errors[:avatar].empty? }
private
def save_avatar_derivatives
self.avatar_derivatives!
end
end
Using this uploader:
# app/uploaders/user_avatar_uploader.rb
require "image_processing/mini_magick"
class UserAvatarUploader < Shrine
plugin :default_storage,
cache: :user_avatar_cache,
store: :user_avatar_store
plugin :store_dimensions
plugin :remote_url, max_size: 20*1024*1024 # 20MB
plugin :validation_helpers
plugin :determine_mime_type
plugin :derivatives
Attacher.validate do
validate_min_size 1, message: "must not be empty"
validate_max_size 5*1024*1024, message: "is too large (max is 5 MB)"
validate_mime_type_inclusion %w[image/jpeg image/png]
end
Attacher.derivatives do |original|
magick = ImageProcessing::MiniMagick.source(original)
{
:"64" => magick.resize_to_fill!( 64, 64, gravity: "Center"),
:"128" => magick.resize_to_fill!(128, 128, gravity: "Center"),
:"256" => magick.resize_to_fill!(256, 256, gravity: "Center"),
:"512" => magick.resize_to_fill!(512, 512, gravity: "Center"),
}
end
end
Everything works fine with valid images, but when the user uploads say a .gif, which doesn’t match the allowed mime types, I correctly get an error message about it. So far, so good.
However, the problem is that in my navbar, I have a link to the user’s profile pic like this:
<img src="<%= current_user.avatar_url(:"256") %>" alt="Avatar image">
So when I re-render my Rails form_with(@user)
while the uploaded avatar has an error, the navbar derivative and the <input type="file">
image preview are both broken due to the invalid @user.avatar
.
One thing I tried is resetting the @user.avatar
and @user.avatar_data
to @user.avatar_was
and @user.avatar_data_was
, but that didn’t work.
Any idea on how I could change my approach to make this work?
Edit: this is using the latest RubyGems version of Shrine (3.3.0) on Rails 6.1.1