0

How can I render a stylesheet per action in rails?

Since my app is not the standart CRUD app, my controllers end up with a few custom routes which require very different CSS's.

So, I'm wondering, is there any way to load the css on a per action basis but still take advantage of the asset pipeline?

Thanks

Nuno
  • 515
  • 1
  • 5
  • 21

3 Answers3

1

create a directory for each of your controllers inside stylesheets directory and create css files corresponding to your action, then put this in you layout file

<%= stylesheet_link_tag "#{params[:controller]}/#{params[:action]}" %>
Saqib
  • 685
  • 3
  • 15
  • With this I believe we're not taking advantage of rails asset pipeline. I've found this [link]http://stackoverflow.com/a/22915786/2517796 here on SO and I believe this is what I'm looking for! – Nuno Dec 01 '15 at 14:52
1

You can use controller specific assets. Just remove the *= require_tree . from application.css. And include the stylesheet the action specific stylesheet in its view by <%= stylesheet_link_tag "style.css" %> but you have to tell rails to compile them by Rails.application.config.assets.precompile = ["style.css"]. You can read more about it here. This way I guess we are using rails assets pipelines just not in default way.

krsoni
  • 539
  • 7
  • 11
0

Add a unique id to the body based on the controller path and action:

Helper:

  def page_id
    "#{controller_path.tr('/', '-')}-#{action_name}".dasherize
  end

Layout:

<body id="<%= page_id %>"...

Then scope your styles to it:

/users/index.scss

#users-index {
  .. page specific styles here ..
}
riley
  • 2,387
  • 1
  • 25
  • 31