Before save Image preview on upload and Remove Image/ Remove Image after save

f -> form-for object/ FormBuilder Object, incase if you wants to use image preview for fields_for then pass fields_for object to image_preview helper method

In html.erb file

<%= image_preview(f) %>

In helper file

def image_preview(f)
	    url, style =  f.object.image.present? ?  [f.object.image.url(:thumb), ''] : ['#','display:none;']
	    content_tag(:div, nil) do
		    concat image_tag url , {id: 'img_prev', style: style}
		    concat ''.html_safe
		    concat  f.button 'Remove', {type: 'button', class: 'remove_image', style:'display:none;'}

In js file

$(function() {

  $(".preview_image").change(function() {

  $(".remove_image").click(function() {
    removeURL(this, $(".preview_image"));

#To show image preview
readURL = function(input) {
  var reader;
  if (input.files && input.files[0]) {
    reader = new FileReader();
    reader.onload = function(e) {
        display: "block"
        display: "block"

#To remove image preview and image from file field.

removeURL = function(remove_button, input) {
    display: "none"
  return $(remove_button).css({
    display: "none"

Reference For Image Preview

Remove Saved Image Carrier Wave:

Case 1: If image column exists in same model

<%= form_for @user, :html => {:multipart => true} do |f| %>
My Image <%= image_tag(@user.image_url) if @user.image? %>
  <%= image_preview(f) %>

 <%= f.check_box :remove_image %> Remove Image 

<% end %>

Case 2: If you used “fields_for” to store image(s) in other model

<%= form_for @user, :html => {:multipart => true} do |f| %>
<%= f.fields_for :images do |pic|%>
<%= get_label_and_field(pic, :picture, 'file_field') %>
<label> Remove <%= pic.check_box :_destroy %> </label>
<%= image_preview(pic) %>

<% end %>
<% end %>

Difference between Case 1 && Case 2 is:

Case 1->;

f.check_box :remove_image 

Case 2->;

pic.check_box :_destroy 

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: , , ,
Posted in html.erb, JQuery, Ruby Little Codes
4 comments on “Before save Image preview on upload and Remove Image/ Remove Image after save
  1. niuxiufeng says:


    can i ask one question?
    i can find 「preview_image」 in your html
    can you tell me how can i add this class(preview_image) to html
    thank you.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: