<%= 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.
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'
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
👍
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With