How do I use Controller specific stylesheets in Rails 3.2.1? How do I use Controller specific stylesheets in Rails 3.2.1? ruby-on-rails ruby-on-rails

How do I use Controller specific stylesheets in Rails 3.2.1?


It can work this way and Marek is quite correct, the answer is in the guide.In the introduction to section 2.1:

For example, if you generate a ProjectsController, Rails will also add a new file at app/assets/javascripts/projects.js.coffee and another at app/assets/stylesheets/projects.css.scss. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as <%= javascript_include_tag params[:controller] %> or <%= stylesheet_link_tag params[:controller] %>.

So to set your application up to load controller specific stylesheets:

First, disable the default loading of all stylesheets by removing any extra requires in the application.css manifest.

Typically you'll see an entry like this:

 *= require_tree .

If you still want to load some common css files, you can move them to a subdirectory and do something like this:

 *= require_tree ./common

Second, In your application's layout add the suggested stylesheet_link_tag eg

<%= stylesheet_link_tag    "application", :media => "all" %><%= stylesheet_link_tag params[:controller] %>

In this example we first load the application css file, we then load any css file that matches the current controller name.


I've solved this problem with a simple solution. I add to body the controller name as a class, editing views/layouts/application.html.slim:

body class=controller.controller_name

Or views/layouts/application.html.erb:

<body class="<%= controller.controller_name%>">

And then in my css I just use body.controller_name as a namespace:

/* example for /users/ */body.users {    color: #000;}body.users a {    text-decoration: none;}

For small projects I think it's fine.


I don't think it works that way (Home.css being applied only to Home controller actions). The different files are just for separation, to make it clearer what are the CSS rules describing. You can read this guide about the asset pipeline. I'm guessing you altered the default application.css.scss and removed the line importing all CSS files from app/assets/stylesheets.