1

I am adding images like this in rails project. I want to check If the image exists and If not I want to use one common image for all the places where the images doesb't exist.

Please help.

          <div class = "col-sm-2"> 
         <center> 
          <%= image_tag pco.printable_photo.url(:small) %>
          <label>
            <%= pco.name %>
          </label>
        </center>
      </div>
R3tep
  • 12,512
  • 10
  • 48
  • 75
Suraj
  • 2,423
  • 12
  • 39
  • 75
  • possible duplicate of [How to check if image exists in Rails?](http://stackoverflow.com/questions/7969241/how-to-check-if-image-exists-in-rails) – R3tep Mar 17 '15 at 09:51
  • thanks a lot for taking my attention there. I searched for js code earlier and hence couldn't land here on this – Suraj Mar 17 '15 at 10:18
  • So this answer maybe help you : http://stackoverflow.com/a/9815854/3083093 – R3tep Mar 17 '15 at 10:22
  • so I Wanted it rails way , so below answer has helped me – Suraj Mar 17 '15 at 10:25

1 Answers1

3

Write a helper method in application_helper.rb:

def print_image(url)
  url = Rails.application.assets.find_asset(url).nil? ? nil : url
  image_tag url || 'default_image.jpg'
end

Then in your view, use this:

<%= print_image(pco.printable_photo.url(:small)) %>

Try to avoid writing logic in your view. Take the help of view helpers.

Sharvy Ahmed
  • 7,247
  • 1
  • 33
  • 46
  • Try this, and let me what it prints, `print_image(pco.printable_photo.url(:small)).inspect` – Sharvy Ahmed Mar 17 '15 at 10:26
  • It worked, I was doing it wrong way, thanks.. now what If I do not want to use helper, method, how do I do that then? – Suraj Mar 17 '15 at 10:27
  • or can you explain me the 2nd line?? url = Rails.application.assets.find_asset(url).nil? ? nil : url – Suraj Mar 17 '15 at 10:28
  • @Suraj, I checked if the image file exists using `Rails.application.assets.find_asset(url).nil?`, this will return true if the image does not exists. Suppose you provided the url from database, but the file somehow has been deleted from filesystem, in that case this checking will help. – Sharvy Ahmed Mar 17 '15 at 10:53
  • @Suraj, And if you don't want to write helper method, then you will have to write logic in your view, which is not a good practice. – Sharvy Ahmed Mar 17 '15 at 10:54
  • @Suraj, if your problem is solved, don't forget to mark it as solved, then it will help others. Good luck. :) – Sharvy Ahmed Mar 17 '15 at 10:58