Instance variables in the controller are passed to the boot file input plugin

I am using bootstrap3 and a special bootstrap plugin called file-input . I use a file-input and a paperclip to attach a photo of a restaurant to my restaurant model.

One of the things I would like to do is allow my users, when editing a restaurant image, to see the old restaurant image (which is stored in @restaurant.image.url

). After reading the documentation, I found that I can set the default image for file input by passing it in source:

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'>",
],

      

I am stuck on how to get mine @restaurant.image.url

in the src attribute of a javascript array, which I can then pass to the file input plugin.

I found this question and it seemed to me that if I turn my file restaurant.js

into a file restaurant.js.erb

, I can just use ruby ​​expressions.

Javascript

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

      

But @restaurant

empty in my javascript file. Does anyone know why?

I am using rails 4, I do not know if this is the difference.

+3


source to share


1 answer


First of all, the files in the assets folder do not have access to the instance variables defined in the controller. However, the views called by your controller are done. One simple solution (though rail purists might beheading me) would be to embed the javascript directly into your form in part.

in _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 have added a default image (since you are using paperclip); change accordingly.

More complex solutions might include gems like gon which can help you pass variables to javascript functions.

0


source







All Articles