3

I'm using bootstrap3 and a particular plugin for bootstrap called file-input. I'm using file-input and paperclip to attach a picture of a restaurant to my Restaurant model.

One of the things I would like to do is have the ability for my users, when editing a restaurant image, to be able to see the old restaurant image (which is stored in @restaurant.image.url). After reading the documentation, I found that I can set a default image to file-input by passing in a source like so:

initialPreview: [
    "<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>",
    "<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>",
],

What I'm stuck on is how do I get my @restaurant.image.url into the src attribute of a javascript array, that I can then pass on into the file-input plugin.

I found this question and it made it seem like if I turn my restaurant.js file into a restaurant.js.erb file I can just use ruby expressions.

javascript

("#image_upload").fileinput( initialPreview: ["<img src='<%= @restaurant.image.url %>' class='file-preview-image'>",]);

But @restaurant is blank in my javascript file. Anyone know why?

I am using rails 4, I don't know if that is the difference.

1 Answer 1

0

First and foremost, files located in the asset folder don’t have access to instance variables defined in the controller. However, views invoked by your controller do. One simple solution (although rails purists might behead me) would be to inline the javascript directly into your form partial.

in your _form.html.erb

<script>
  $(document).ready(function(){
      img_source = "#{defined?(@restaurant) && @restaurant.image.exists? ? @restaurant.image.url : image_url('default_image.jpg')}"
      $("#image_upload").fileinput( initialPreview: ["<img src='"+img_source+"' class=\'file-preview-image\'>"]);
});
</script>

Note: I did add a default image (since you are using paperclip); modify accordingly.

More complicated solutions might involve gems such as gon which can help you pass variables to javascript functions.

Sign up to request clarification or add additional context in comments.

1 Comment

If I were to put the javascript in a partial, could that be done? Would I have to put that in the views folder, or could I put it in the assets folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.