LoginSignup
5
12

More than 5 years have passed since last update.

Railsでcssをコントローラー単位で読み込む

Last updated at Posted at 2018-04-21

rails g controller hogeでviewは自動でcontroller毎にフォルダ管理されるけど、cssはされず、全てのcssファイルを読み込んでしまいます。

せっかく、viewはcontroller毎に管理してあるのだから、stylesheetもcontroller毎に管理したい。

  • まずは、//= require_treeを削除する
application.scss
/*
 * 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 bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 * 
 *= require_self
 */

この時、require_selfは残しておいて良い

  • stylesheetのフォルダを作成する

viewsでのフォルダ管理と同じように、
cssに関してもフォルダを作成し、その中に適用したいファイルを保存するようにします。
今回は、usersControllerとTopControllerがあると仮定して、下記のようなディレクトリ構造にしました。

app/
  ├ assets/
  |  └ stylesheets/
  |       └ application.scss
  |       ├ user
  |       ├ top
  |
  ├ views/
     └ layouts
     ├ user
     ├ top

  • viewファイルにstyleSheet_link_tagを記述

viewのtopフォルダにindex.html.erbがあるとして、styleshhetのtop/index.scssを読み込みたいとすると、下記の様に記述します

index.html.erb
 <%= stylesheet_link_tag "top/index", :media => "all" %>
  • プリコンパイルに追加する。

これはcssならしなくて良いのですが、scssを使うならプリコンパイルに追加する必要があります。

config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( top/index )

これをしないとエラーが出るので、注意です。

一応、任意のスタイルシートだけを適用できる様になったけど、もっとよくて簡単な方法ある気がする、、、

5
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
12