仅呈现特定于控制器的样式表在第一次请求时不起作用

rendering only controller-specific stylesheets not working on first request

在我的应用程序中,我有很多控制器和大量的 css,如果将它们放在一起可能会发生冲突。因此,我在控制器到控制器的基础上链接我的样式表。 Rails 指南中的 Ruby 建议如下:

You can also opt to include controller specific stylesheets and JavaScript files only in their respective controllers using the following:

%= javascript_include_tag params[:controller] %> or <%= stylesheet_link_tag params[:controller] %>

(由于 Stack Overflow 块引号,我不得不从 <%= 中省略第一个 <。)

因此,这是我的 application.html.erb 文件的结果头部:

<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag params[:controller] %>
<%= stylesheet_link_tag params[:controller] %>

我已经为导航栏共享了 css,它在我的 application.css 文件中是 @import[ed],它总是工作正常。导航栏的样式始终正确。 问题是,当我访问特定页面时,在 first 页面请求中,未加载与该控制器相关的 css。在日志中,从未对控制器的样式表发出请求。但是在 second 页面请求中,它得到了样式,并且日志显示请求了样式表。

这是什么原因?

下面是这个问题的一些相关代码:

/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 */
@import 'normalize';
@import 'sass_vars';
@import 'sitewide';
@import "https://fonts.googleapis.com/css?family=Nunito:300,400,700";

在我的 config/initializers/assets.rb 中,我将 javascript 和 css 文件的所有名称添加到行

Rails.application.config.assets.precompile += ......

如果您不使用 Turbolinks,请将其从您的项目中删除。它包括:

  • 正在删除 turbolinks gem
  • 从 application.js 和 application.css
  • 中删除要求
  • 正在从布局中删除 data-turbolinks-track 属性

并考虑将 rails new --skip-turbolinks 用于您的下一个项目。