如何检查Rails中是否存在图像?

 

你怎么检查是否有这样的图像,如果没有,那么什么都不显示?

在Rails 3.07中工作。

你可以使用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 

由于Rails 4以来Rails资产管道的变化,其他答案有点过时了。以下代码适用于Rails 4和5:

如果您的文件放在公共目录中,则可以使用以下命令检查其存在:

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

但是,如果文件放在assets目录中,那么由于生产环境中的资产预编译,检查存在会有点困难。 我推荐以下方法:

 # 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' 

你可以使用File.file吗? 方法。

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

你也可以使用File.exist? 方法,但如果找到目录或文件,它将返回true。 方法文件? 比存在更挑剔?

对于Rails 5来说,对我有用的是

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

如果资产不存在则返回nil如果存在则返回path_of_the_asset

👍