Parker Parker - 1 year ago 73
Ruby Question

rendering only controller-specific stylesheets not working on first request

In my application, I have many controllers and tons of css which could potentially be conflicting if plopped all together. Because of this I am linking my stylesheets on a controller-to-controller basis. The Ruby on Rails Guides suggests the following:

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] %>

(I had to omit the first < from <%= because of Stack Overflow block quotes.)

Therefore, here is the resulting head of my application.html.erb file:

<%= 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] %>

I have shared css for a navigation bar, which is @import[ed] in my application.css file, and that always works fine. The navigation bar is always styled properly.
The problem is, when I visit a specific page, on the first page request, the relevant css to that controller isn't loaded. And in the logs, a request is never made for the controller's stylesheets. But on the second page request, it gets styled, and the logs reveal that the stylesheets were requested.

Any reason why this is?

Below is some relevant code to this issue:

* 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 ",400,700";

And in my config/initializers/assets.rb I added all of the names of my javascript and css files to the line

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

Answer Source

If you are not using Turbolinks, remove it from your project. It includes:

  • removing turbolinks gem
  • removing requires from application.js and application.css
  • removing data-turbolinks-track attribute from your layout

And consider using rails new --skip-turbolinks for your next project.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download