Ruby on Railsで管理画面とユーザーが閲覧する画面でlayoutを分けるようなケースが一定あると思いますが、
その際に以下のようにlayouts配下にディレクトリを切っていくとApplicationController
とAdmin::ApplicationController
でControllerを分けた際にRailsがよしなにlayouts配下のapplicaiton.html.erb
とadmin/application.html.erb
を利用してくれるので便利です。
$ tree app/views app/views ├── layouts │ ├── application.html.erb │ └─admin │ └── application.html.erb
2.2.14 Finding Layouts
To find the current layout, Rails first looks for a file in app/views/layouts with the same base name as the controller. For example, rendering actions from the PhotosController class will use app/views/layouts/photos.html.erb (or app/views/layouts/photos.builder).
Layouts and Rendering in Rails — Ruby on Rails Guides
しかし、だんだん大きくなってくると全てのレイアウトがlayoutsファイルに溜まっていきどこで利用されているものか分かりにくくなったりするので、以下のような感じでトップレベルのディレクトリ単位で分ける方法をメモ🗒
$ tree app/views app/views ├── admin │ └── layouts │ └── application.html.erb ├── layouts │ └── application.html.erb
やり方は簡単でController内でlaytout
を使って明示的に指定してあげれば大丈夫だった🙆♂️
# frozen_string_literal: true class Admin::ApplicationController < ApplicationController layout 'admin/layouts/application' end
Ruby on Rails便利ですね!