【问题标题】:Why are images not showing in Rails app deployed on Heroku?为什么在 Heroku 上部署的 Rails 应用程序中没有显示图像?
【发布时间】:2018-09-23 21:55:37
【问题描述】:

我在这里尝试了许多类似问题的解决方案,但到目前为止都没有奏效。起初我想我可能需要迁移数据库或预编译资产,所以我尝试了:

rails assets:precompile
bundle exec rake assets:precompile RAILS_ENV=production
heroku run rails db:migrate

每次我推送到 git 和 heroku 之后,页面和导航栏的背景图像仍然没有显示。

我对这个问题也有一些怀疑,但我需要帮助调查它们。图像在 css 文件中,而不是在应用程序布局中,所以这可能是原因,但我原以为 application.scss 中的 require tree. 会自动包含所有样式表。

pages.scss:

body {
    margin: 0;
    padding: 0;
    text-align: justify;
    font: 12px Arial, Helvetica, sans-serif;
    font-size: 13px;
    color: #061C37;
    background: #F7F8ED;
    background-image:url('background2.png');
    background-repeat:repeat-x;
}

#menu
{
background-image:url('menu.png');
background-repeat:no-repeat;
width:720px;
height:49px;
clear:both;
}

application_layout.rb:

<!DOCTYPE html>
<html>
  <head>
    <title>Site1</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <h1 class="off2">Nutricion</h1>
    <h2 class="off3">Simón Verde</h2>

<div id="container">
    <div id="menu">
      <ul>
        <li class="menuitem">
          <%= link_to 'Inicio', pages_inicio_path %>
        </li>
        <li class="menuitem">
          <%= link_to 'Page1', pages_page1_path %>
        </li>
        <li class="menuitem">
          <%= link_to 'Page2', pages_page2_path %>
        </li>
        <li class="menuitem">
          <%= link_to 'Page3', pages_page3_path %>
        </li>
        <li class="menuitem">
          <%= link_to 'Contacto', pages_contacto_path %>
        </li>
      </ul>
    </div>
    </div>

<div id="content">

    <%= yield %>

</div>
  </body>
</html>

开发中的页面(图像可以工作)和生产页面(图像不工作的地方)的 html 也不同。如下所示,资产似乎没有正确加载。我注意到,当我预编译资产时,它们被编译在 public/assets 文件夹中,而不是 app/assets 文件夹中。这有什么不同吗?如果是这样,为什么要这样做,我该如何继续?还需要简要说明为什么需要进行资产预编译,以便更好地了解这里出了什么问题。

我注意到的最后一件事是public/assets 文件夹中的图像文件名称与app/assets 文件夹中的图像文件名称不同,即menu.png 已自动更改为menu-longlistofrandomcharacters.png,因此这可能会影响图片。

来自开发的 html 源代码(工作图像):

<!DOCTYPE html>
<html>
  <head>
    <title>Site1</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="FaSScd+v4DcF0Qw1F+J4ncgTPYFVtZnGVSmbPLAbRepnLZWX5CVZ4Seu7MtM7zi9S/xvXAkX9C9S8PBaljPFag==" />

    <link rel="stylesheet" media="all" href="/assets/application-6c72f0201f5f7b2ee273bd419a0b5c2a9e23f4d82d24ac305819a8f8823d7041.css" data-turbolinks-track="reload" />
    <script src="/assets/application-5c96b667d84f4b133f713cdb7f070ec1c66c023d7b9a7c4da42e893764b2391e.js" data-turbolinks-track="reload"></script>
  </head>

  <body>
    <h1 class="off2">Nutricion</h1>
    <h2 class="off3">Simón Verde</h2>

<div id="container">
    <div id="menu">
      <ul>
        <li class="menuitem">
          <a href="/pages/inicio">Inicio</a>
        </li>
        <li class="menuitem">
          <a href="/pages/page1">Page1</a>
        </li>
        <li class="menuitem">
          <a href="/pages/page2">Page2</a>
        </li>
        <li class="menuitem">
          <a href="/pages/page3">Page3</a>
        </li>
        <li class="menuitem">
          <a href="/pages/contacto">Contacto</a>
        </li>
      </ul>
    </div>
    </div>

<div id="content">

    <h1>Pages#inicio-</h1>
<p>Find me in app/views/pages/inicio.html.erb</p>


</div>
  </body>
</html>

生产中的 html 源代码(非工作图像):

<!DOCTYPE html>
<html>
  <head>
    <title>Site1</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="GS80dnfxoO5mgrdm82ZPYZYf812BdzCUVEzCJ3bK94RMII673xzCG9UxNLxcmj/RzmuZXH/y7lWCXvP2DbaVMA==" />

    <link rel="stylesheet" media="all" href="/assets/pages.self-36f0aba003234ddc45e8dc02c89942085fbc533a2591c1fef108462ef36733ce.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/application.self-af04b226fd7202dfc532ce7aedb95a0128277937e90d3b3a3d35e1cce9e16886.css?body=1" data-turbolinks-track="reload" />
    <script src="/assets/jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/jquery_ujs.self-784a997f6726036b1993eb2217c9cb558e1cbb801c6da88105588c56f13b466a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-2db6ec539b9190f75e1d477b305df53d12904d5cafdd47c7ffd91ba25cbec128.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-5454023407ffec0d29137c7110917e1e745525ae9afbc05f52104c4cd6597429.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-6e0514260c1aa76eaf252412ce74e63f68819fd19bf740595f592c5ba4c36537.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/pages.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-b89234cf2659d7fedea75bca0b8d231ad7dfc2f3f57fcbaf5f44ed9dc384137b.js?body=1" data-turbolinks-track="reload"></script>
  </head>

  <body>
    <h1 class="off2">Nutricion</h1>
    <h2 class="off3">Simón Verde</h2>

<div id="container">
    <div id="menu">
      <ul>
        <li class="menuitem">
          <a href="/pages/inicio">Inicio</a>
        </li>
        <li class="menuitem">
          <a href="/pages/page1">Page1</a>
        </li>
        <li class="menuitem">
          <a href="/pages/page2">Page2</a>
        </li>
        <li class="menuitem">
          <a href="/pages/page3">Page3</a>
        </li>
        <li class="menuitem">
          <a href="/pages/contacto">Contacto</a>
        </li>
      </ul>
    </div>
    </div>

<div id="content">

    <h1>Pages#inicio-</h1>
<p>Find me in app/views/pages/inicio.html.erb</p>


</div>
  </body>
</html>

config/production.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Mount Action Cable outside main process or domain
  # config.action_cable.mount_path = nil
  # config.action_cable.url = 'wss://example.com/cable'
  # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :debug

  # Prepend all log lines with the following tags.
  config.log_tags = [ :request_id ]

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Use a real queuing backend for Active Job (and separate queues per environment)
  # config.active_job.queue_adapter     = :resque
  # config.active_job.queue_name_prefix = "site1_#{Rails.env}"
  config.action_mailer.perform_caching = false

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Use a different logger for distributed setups.
  # require 'syslog/logger'
  # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new(STDOUT)
    logger.formatter = config.log_formatter
    config.logger = ActiveSupport::TaggedLogging.new(logger)
  end

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false
end

有人能解释一下为什么所有额外的html标签行都不会出现在非工作版本上吗?

【问题讨论】:

  • 图像不在根目录中,所以它们不会显示是有道理的
  • @WilliamHampshire 的“根目录”是指应用程序目录吗?因为他们在里面。只是在预编译 Rails 时自动使用了公共目录。我不知道该怎么办
  • 你能显示你为#menu 渲染的HTML 代码吗?查看背景图片是否有正确的 url。
  • @EJ2015 我编辑了 html 文件以显示页面的完整输出。在工作或非工作页面的 html 输出中似乎没有提到背景图像。但是图像 url 来自样式表而不是应用程序布局。这会导致它不出现吗?

标签: ruby-on-rails heroku


【解决方案1】:

经过搜索,我偶然发现了一个解决方案,但不知道为什么会奏效。

bundle exec rake assets:precompile 工作并使图像出现。

我之前尝试过

bundle exec rake assets:precompile RAILS_ENV=production

这解决了我的问题,但我不知道命令 bundle exec rake assets:precompile RAILS_ENV=production 是否也没有解决问题,因为我认为就 Heroku 而言它正在做同样的事情。另一个令人困惑的事情是 html 输出与原始问题中的上述相同。包括差异,即使页面看起来与包含的图像相同。

如果有人可以评论为什么这个解决方案有效,它可以改善其他有相同问题的人的答案,也可以帮助我了解哪里出了问题。

【讨论】:

    【解决方案2】:

    您应该将图片保存在 /assets/images 中。并在您的 CSS 中使用 image-url 而不是 url。这是 Rails 为资产管道提供的帮助程序,将自动生成文件的正确路径。

    文件的名称更改是由于附加了资产管道的指纹,资产管道将这些文件生成到 /public 文件夹中,因为这是提供静态文件的根目录。在开发中,情况有所不同,css 和 js 是分开提供的。我认为this 会帮助你理解。

    【讨论】:

    • 将 background-image:url('menu.png') 更改为 background-image:image-url('menu.png'),但在将更改推送到 heroku 后并没有什么不同。另外,是的,图片已经在 assets/images 中
    • 可以尝试设置config.serve_static_assets = true。如果你不使用 Nginx 或 Apache,你可能需要adjust config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
    • config.serve_static_assets 设置在哪里?我在 production.rb 文件中没有看到它,我应该在 config.public_file_server.enabled 设置中调整什么?还有我如何知道我使用的是 Nginx 还是 Apache,它们是什么?
    • 这些是 Web 服务器。如果你没有设置它们,你就没有使用它们。抱歉,请忘记 serve_static_assets。它已被弃用。您可以尝试将另一个更改为 config.public_file_server.enabled = true (或者最好将heroku上的ENV变量'RAILS_SERVE_STATIC_FILES'设置为非空白)。这应该使 Rails 能够提供静态文件。
    • 我尝试了 config.public_file_server.enabled = true 但仍然没有图像。 heroku 上的“RAILS_SERVE_STATIC_FILES”表示“已启用”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多