Rails4 アクション毎にレイアウトを変更する
アクション毎にレイアウトを変更しようとして、1度失敗したので、メモ。
下記の2つのレイアウトファイルを作成した。
app/views/layouts/basic.html.erb
app/views/layouts/custom.html.erb
indexにbasic.html.erbのレイアウト、showにcustom.html.erbのレイアウトを適用しようと、下記のように記載した。
class UsersController < ApplicationController layout 'basic', only: [:index] layout 'custom', only: [:show]
結果は、showにはcustom.html.erbのレイアウトが適用されたが、indexにはレイアウトが適用されなかった。
アクション毎にレイアウトを適用したい場合は、下記のようにrenderを使う。
def index @users = User.all render layout: 'basic' end def show render layout: 'custom' end
※アクションの最後にrenderを記載すること。