在使用Active Storage上传附件时,如果服务器在上传后停止运行,可能是由于mimemagic gem导致的。为了解决这个问题,可以使用如下代码:
gem 'mimemagic', '~> 0.3.10'
bundle install
config.active_storage.service = :local
config.autoload_paths += %W(#{config.root}/lib)
class MimeType
def self.lookup_by_extension(extension)
mime_types = MIME::Types.type_for(extension)
return nil if mime_types.empty?
mime_types.first.content_type
end
end
def create
@post = Post.new(post_params)
blob = ActiveStorage::Blob.create_after_upload!(
io: params[:post][:image],
filename: params[:post][:image].original_filename,
content_type: MimeType.lookup_by_extension(File.extname(params[:post][:image].original_filename)).to_s
)
@post.image.attach(blob)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
这样,就能够解决Active Storage附件上传后,Rails服务器停止运行的问题。