When the user's image was changed, it was difficult to tell whether the file was raised but clearly changed, so I used jQuery to preview it nicely (I'm not good at the front ...).
ruby 2.6.3 rails 6.0.3 Uploader ActiveStorage jQuary
Before uploading the file: Preview the image already associated with the user After uploading the file: Hide the display of the image already associated with the user, Preview new image file
users ①edit.html.slim ②_form.html.slim (Only the form part is cut out and used. There is no problem even if you write everything in edit.) ③javascripts/app/users/edit.js
edit.html.slim
- content_for :title
= I18n.t 'helpers.title.edit', model: t_model(:user), name: @user.name
== render 'form', model: @user
_form.html.slim
= render 'shared/validation_messages', model: model
= simple_form_for model, html: { class: 'form-horizontal js-editing' } do |f|
.page-content.container.profile_edit
.card
.card-header
h5.card-title
|Basic information
.card-body.p-3.ibox-content
.no-padding.no-margins
.circle-avatar
img src="#" id="avatar_img_prev" class="d-none"
- if model.image.attached?
= image_tag(model.image, class: 'avatar_present_img')
- else
= image_tag("defaurt-user.png ", class: "avatar_present_img")
|
br
= f.file_field :image, id: "post_img"
= f.input :name, placeholder: 'Hanako Yamada'
/The following is omitted
javascripts/app/users/edit.js
/* global $ */
$(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#avatar_img_prev').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$("#post_img").change(function(){
$('#avatar_img_prev').removeClass('d-none');
$('.avatar_present_img').remove();
readURL(this);
});
}());
・ The way to write ʻimg in slim notation is not ʻimg src:" ~~ ", id:" ~~ "
, but ʻimg src =" ~~ "id =" ~~ "` (rarely) I didn't understand because I didn't write it ...).
・ ʻImg src = "#" id = "avatar_img_prev" class = "hidden" class was not reflected well, so changed to
class = "d-none" `→ It worked
-Since jQuary was written on form.slim and was not reflected well, it was properly rewritten in the js file.
[Rails5] Immediate preview of uploaded image
Web app tsunagaru released [4] Migrating from ActiveStorage to CarrierWave
Thorough explanation of how to use the Bootstrap4 display class