How to check if image exists in Rails?

2019-02-21 13:31发布

问题:

<%= 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.

回答1:

You can use File.exist?.

if FileTest.exist?("#{RAILS_ROOT}/public/images/#{img}")
  image_check = image_tag("#{img}",options)
else
  image_check = image_tag("products/noimg.gif", options)
end


回答2:

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'


回答3:

You can use File.file? method.

if File.file?("#{Rails.root}/app/assets/images/{image_name}")
  image_tag("#{image_name}")
end

You can also use File.exist? method but it will return true if it finds a directory or a file. The method file? is slightly more picky than exist?



回答4:

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