Rails - 当使用image_tag时,资产不在资产管道中

25

目标:在生产环境中使用我的Rails应用程序和静态图像资源

步骤:

  1. 将我的Rails应用程序切换到生产环境。
  2. 使用RAILS_ENV=production rails assets:precompile预编译资产。
  3. 设置RAILS_SERVE_STATIC_FILES环境变量为true,以启用公共文件服务器(在production.rb中 - config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
  4. /config/application.rb中添加config.serve_static_assets = true

通过这种设置,我已经启动了服务器。

我有一些静态图像在/app/assets/images/中,预编译版本的指纹文件名现在在/public/assets中。例如:

  • aussen-d2fb0029a12281121a1752c599e715a8e2b3db17f1e8e18248a79a7b1ca63b91.jpg
  • hintergrund-ca80e1ae5a697c86898f3a7e107694a76dc12e54320b8ac80c58eecbffe0414a.png

目前为止一切都很好。

当我在application.css.erb中使用background-image: url(<%= asset_path('hintergrund') %>);时,它成功地从/public/assets加载预编译的背景图像。

问题:我无法通过视图中的image_tags访问预编译的图像!例如:

<%= image_tag("aussen") %>

错误日志:

I, [2018-03-23T00:46:29.133381 #9289]  INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Started GET "/" for 46.142.136.81 at 2018-03-23 00:46:29 +0100
I, [2018-03-23T00:46:29.134466 #9289]  INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Processing by HomeController#index as HTML
I, [2018-03-23T00:46:29.136604 #9289]  INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]   Rendering home/index.html.erb within layouts/application
I, [2018-03-23T00:46:29.138267 #9289]  INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]   Rendered home/index.html.erb within layouts/application (1.5ms)
I, [2018-03-23T00:46:29.138482 #9289]  INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Completed 500 Internal Server Error in 4ms
F, [2018-03-23T00:46:29.139546 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]
F, [2018-03-23T00:46:29.139635 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] ActionView::Template::Error (The asset "aussen" is not present in the asset pipeline.):
F, [2018-03-23T00:46:29.139798 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]     1: <%= image_tag("aussen", id: "home-img", alt: "Aussenansicht von Simson-Seelig") %>
[f36ff000-6261-4c2c-bfcc-4a2f80cae682]     2: <div id="home" class="content">
[f36ff000-6261-4c2c-bfcc-4a2f80cae682]     3:   <p>Alles für Simson von Simson-Seelig.</p>
[f36ff000-6261-4c2c-bfcc-4a2f80cae682]     4:   <p>Für die legendären Schwalben und alle anderen SIMSON-Modelle bieten wir Ersatzteile und Service. </p>
F, [2018-03-23T00:46:29.139867 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]
F, [2018-03-23T00:46:29.139930 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] app/views/home/index.html.erb:1:in `_app_views_home_index_html_erb__177499641769

经过数小时的研究,我仍然不明白为什么我可以在样式表中访问预编译图像,却无法在带有image_tag的视图中访问它。
其他信息:
$ ruby --version
ruby 2.4.3p205 (2017-12-14 revision 61247) [x86_64-linux]

$ rails --version
Rails 5.1.4

/config/application.rb:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module SimsonSeelig
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Enable rails to serve my assets
    config.serve_static_assets = true
  end
end

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

  # Attempt to read encrypted secrets from `config/secrets.yml.enc`.
  # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
  # `config/secrets.yml.key`.
  config.read_encrypted_secrets = 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?

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

  # 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 = "simson-seelig_#{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

/config/initializers/assets.rb:

# Be sure to restart your server when you modify this file.

# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'

# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )

不应该有任何区别。请看我在被接受的答案下面的评论。 - Vega180
6个回答

31

资产 "aussen" 不在资产管道中。

从技术上讲,这是正确的,因为您没有 aussen 这个资产,但是您有 aussen.jpg ,所以应该使用 <%= image_tag("aussen.jpg") %>

请注意,如果您使用 <%= image_tag("aussen") %> ,那么将会生成类似于以下 HTML:

<%= image_tag("aussen") %>
#=> <img alt="Aussen" src="/assets/aussen" />

使用<%= image_tag("aussen.jpg") %>会生成如下HTML代码

<%= image_tag("aussen.jpg") %>
#=> <img alt="Aussen" src="/assets/aussen.jpg" />

当进入生产模式时,页面源代码会显示一些加密的密钥,就像这样

aussen-d2fb0029a12281121a1752c599e715a8e2b3db17f1e8e18248a79a7b1ca63b91.jpg

image_tagAssetTagHelper 可供参考。

production.rb文件中的 config.assets.compilefalse 更改为 true

# config/environments/production.rb
...
config.assets.compile = true
...

4
config.assets.compile = true 这就解决了问题!非常感谢! - Vega180
1
<%= image_tag("aussen") %> works. It points to <img src="/assets/aussen-d2fb0029a12281121a1752c599e715a8e2b3db17f1e8e18248a79a7b1ca63b91.jpg" > - Vega180
1
太棒了!和真棒 :) - fool-dev
6
这会让你的生产应用程序暴露于严重的漏洞之中。不要这样做 - jakenberg
1
image_tag("aussen")在开发中可以正常工作而不需要文件扩展名,这可能是不期望的行为。最好的做法是:指定完整的文件名,并且在生产环境中将config.assets.compile = false - Pathogen

17

不确定是否想在生产环境中设置config.assets.compile = true,这将减慢服务器速度。

config.assets.compile=true在Rails生产环境中,为什么不呢?

与其明确地设置config.assets.compile = false,还不如将其注释掉,这对我有用,这可能是一个错误。注释掉后,使用预编译资产管道正确渲染了图像。

# config.assets.compile = false

17

当上述方法均无效时,以下是解决方案。

你是否在引用一个.jpeg文件?.jpeg文件会被编译为.jpg文件,因此如果你引用.jpeg文件,则会出现此错误。

解决方案是将文件重命名为.jpg,并使用相应的.jpg扩展名引用image_tag


2
今天的救星。 - Hegwin
1
天啊,在我的情况下就是这样。 - januszm
我可以确认,在Rails 7中仍然存在这个问题 - jpEg转换为jpg,导致你的生产环境失败。 - Denis
哇。对我来说也是这样。谢谢! - Tim Fletcher

8

当我在Ubuntu 20.04上开发使用Rails 6应用程序时,遇到了同样的问题。

对我来说,问题是我在生产环境中没有预编译资产。

以下是我的解决方法:

首先,我运行以下命令来预编译资产并使它们在应用程序的public目录中可用:

rails assets:precompile RAILS_ENV=production

注意:在开发中,可以使用webpacker命令来实现此操作:/bin/webpack-dev-server

接下来,设置NginxApache Web服务器以提供我应用程序的public目录中可用的静态文件。对我来说,我使用以下配置设置了Nginx,并使用Let's Encrypt进行SSL:

upstream railsserver {
        server 127.0.0.1:3000;
}

server {

        # Replace 'localhost' with your FQDN if you want to use
        # your app from remote or if you need to add a certificate 
        server_name my-website.com www.my-website.com;
                        
        root /home/deploy/my-website/public;

        # Define where Nginx should write its logs
        access_log /var/log/nginx/my-website/access.log;
        error_log /var/log/nginx/my-website/error.log;

        location / {
            # First attempt to serve request as file, then
            # the rails application directory
            try_files $uri @railsserver;
        }
       
        location ~ ^/(assets/|robots.txt|humans.txt|favicon.ico) {
                expires max;
        }

        location @railsserver {
                proxy_set_header Host $http_host;
                proxy_set_header CLIENT_IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_read_timeout 300;
                proxy_pass http://railsserver;

                gzip on;
                gzip_types text/plain text/xml text/css image/svg+xml application/javas$
                gzip_proxied any;
        }

        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/my-website.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/my-website.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

我希望您能从中获得所需的帮助。

就是这样了。


2
如果链接含义不明确,可以参考这个链接:
image_tag '#', skip_pipeline: true

0

如果您的图像放错地方,也会发生这种情况。对于 Rails 6,请将图像放在/app/assets/images/中,然后简单地

<%= image_tag("logo1.png", alt: "My logo", size: '200x75') %>

如果在使用ActiveStorage时出现问题,使用this应该可以解决:

<%= video_tag url_for(@banner_video.file), size: "150x120", controls: true %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接