How to check if image exists in Rails?

前端 未结 4 1811
再見小時候
再見小時候 2021-01-11 12:39
<%= 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 disp

相关标签:
4条回答
  • 2021-01-11 13:16

    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
    
    0 讨论(0)
  • 2021-01-11 13:22

    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'
    
    0 讨论(0)
  • 2021-01-11 13:24

    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?

    0 讨论(0)
  • 2021-01-11 13:26

    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

    0 讨论(0)
提交回复
热议问题