Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if image exists in Rails?

<%= image_tag("/images/users/user_" + @user_id.to_s + ".png") %>

How do you check to see if there is such an image, and if not, then display nothing?

Working in Rails 3.07.

like image 749
B Seven Avatar asked Nov 01 '11 16:11

B Seven


2 Answers

The other answers are a little outdated, due to changes in the Rails asset pipeline since Rails 4. The following code works in Rails 4 and 5:

If your file is placed in the public directory, then its existence can be checked with:

# File is stored in ./public/my_folder/picture.jpg
File.file? "#{Rails.public_path}/my_folder/picture.jpg"

However, if the file is placed in the assets directory then checking existence is a little harder, due to asset pre-compilation in production environments. I recommend the following approach:

# File is stored in ./app/assets/images/my_folder/picture.jpg

# The following helper could, for example, be placed in ./app/helpers/
def asset_exists?(path)
  if Rails.configuration.assets.compile
    Rails.application.precompiled_assets.include? path
  else
    Rails.application.assets_manifest.assets[path].present?
  end
end

asset_exists? 'my_folder/picture.jpg'
like image 154
Tom Lord Avatar answered Sep 27 '22 20:09

Tom Lord


For Rails 5 the one that worked for me is

ActionController::Base.helpers.resolve_asset_path("logos/smthg.png")

returns nil if the asset is absent and path_of_the_asset if present

👍

like image 32
Antoine Avatar answered Sep 27 '22 22:09

Antoine