图片未在 Rails 开发环境中加载

Images do not load in Rails development Environment

我有下面一行代码:

<img src="<%= image_url ("/slides/hotel.jpg") %>" style="opacity:0;" alt="slidebg1" data-bgfit="cover" data-bgposition="left bottom" data-bgrepeat="no-repeat">

Gemfile:

source https://rubygems.org
gem 'rails', '4.2.3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'pg', '~> 0.18.2'
gem 'coffee-script-source', '1.8.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'simple_form'
gem 'headjs-rails'

group :development, :test do
  gem 'debugger'
  gem 'activerecord-postgresql-adapter'  gem 'web-console', '~> 2.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Development.rb:

config.assets.debug = false
config.assets.compile = true
config.assets.enabled = true
config.serve_static_assets  = true

我 运行 在 Windows 8 我给了 rake assets:precompile 并且完成得很好。但是图像不会加载。我确定该图像存在于该指定目录下。在我的例子中,图像存在于 assets/images/slides/hotel.jpg 下。我曾尝试将文件路径指定为 /assets/images/slides/hotel.jpg/images/slides/hotel.jpg/slides/hotel.jpg,但所有 3 个都不起作用。

错误:

Started GET "/slides/hotel.jpg" for ::1 at 2015-07-28 21:03:04 +0530
ActionController::RoutingError (No route matches [GET] "/slides/hotel.jpg")

你为什么不用image_path

例如

<%= image_path "/slides/hotel.jpg", style:"opacity:0;", alt:"slidebg1", 'data-bgfit'=>"cover", 'data-bgposition'=>"left bottom" 'data-bgrepeat'=>"no-repeat"%>

我会尝试其他两种变体:

(1) image_url ("slides/hotel.jpg")(我无法想象这是最基本的,而且 image_url 正在添加一个额外的斜杠...)

(2) asset_url ("hotel.jpg")

试试这个

在 application.rb 中,添加以下行:

config.assets.enabled = true

如果 slides 目录在 assets 目录中,则

config.assets.paths << Rails.root.join("app", "assets", "slides")

如果幻灯片目录在 assets/images 目录中,则

config.assets.paths << Rails.root.join("app", "assets", "images", "slides")

然后尝试加载图片

<%= assets_path "/slides/hotel.jpg", style:"opacity:0;", alt:"slidebg1", 'data-bgfit'=>"cover", 'data-bgposition'=>"left bottom" 'data-bgrepeat'=>"no-repeat"%>

希望这对你有用。

在您的情况下,图像存在于 assets/images/slides/hotel.jpg 下,因此 image_url 返回的路径必须是 /images/slides/hotel.jpg(有关 guide 中资产路径的更多信息)

解法:

<img src="<%= image_url('slides/hotel.jpg') %>" style="opacity:0;" alt="slidebg1" data-bgfit="cover" data-bgposition="left bottom" data-bgrepeat="no-repeat">
#                        ^---- Just remove the "/" here

我是怎么发现的:

小红包,帮你一探究竟,下次运行遇到类似情况

从您的 rails 应用程序目录,在终端中启动 rails c

# Include the helper whom define image_url
irb(main):001:0> include ActionView::Helpers::AssetUrlHelper
=> Object

# Test the output of your actual code
irb(main):002:0> image_url "/slides/hotel.jpg"
=> "/slides/hotel.jpg"
# As you can see the path is incorrect because it does not start with '/images'

# Test the output after removing the heading slash
irb(main):003:0> image_url "slides/hotel.jpg"
=> "/images/slides/hotel.jpg"
# Correct output as the path starts with '/images'