0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Railsでアクションごとにレイアウトを設定する方法

Posted at

Railsでアクションごとにレイアウトを設定したい場面って結構あるので、解説とかありませんが、方法だけお伝えしたいと思います。

class ProfilesController < ApplicationController
    layout :resolve_layout
    def new
        @profile = Profile.new
    end
    
      def show
        @profile = Profile.find(params[:id])
      end
    
      def edit
        @profile = Profile.find(params[:id]) 
      end

      private
      def resolve_layout
        case action_name
        when "new", "edit"
          "devise"
        when "show"
          "main"
        else
          "application"
        end
      end
end

まぁこんな感じでです。
特に大切な部分は

layout :resolve_layout #レイアウトの設定
#〜省略~
private #アクションごとにどれのレイアウトにするか設定
def resolve_layout
  case action_name
  when "new", "edit"
    #アクションがnew or editのとき
    "devise"
  when "show"
    #アクションがshowのとき
    "main"
  else
   #それ以外
   "application"
  end
end

でしゅ。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?