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

B S*_*ven 11 filesystems ruby-on-rails image ruby-on-rails-3

<%= image_tag("/images/users/user_" + @user_id.to_s + ".png") %>
Run Code Online (Sandbox Code Playgroud)

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

在Rails 3.07中工作.

Ami*_*far 16

你可以使用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
Run Code Online (Sandbox Code Playgroud)


Tom*_*ord 9

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

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

# File is stored in ./public/my_folder/picture.jpg
File.file? "#{Rails.public_path}/my_folder/picture.jpg"
Run Code Online (Sandbox Code Playgroud)

但是,如果文件放在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'
Run Code Online (Sandbox Code Playgroud)


Ant*_*ine 7

对于Rails 5,对我有用的是

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

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