LoginSignup
3
4

More than 5 years have passed since last update.

Controller を作らないで View を追加したい

Posted at

やりたい事:「Visual Regression Testing に使いたい」「実装前のサンプルにしたい」などの理由で、 View を追加する時に Controller や routes を書かないで済むようにする

今回の条件

  • /tests/ 以下はテスト用
  • /tests/admin/ 以下は管理画面用
  • 管理画面とそれ以外で別のレイアウトを使いたい

tests 微妙……とは思っています。

routes を書く

ワイルドカードを使う。
参考:3.11 ルーティンググロブとワイルドカードセグメント | Rails のルーティング

routes.rb
Rails.application.routes.draw do
  if Rails.env.development?
    get 'tests/*path', to: 'tests#show'
  end
end

Controller を書く

/tests/admin/xxx だったら、layouts/admin を使う。

tests_controller
class TestsController < ApplicationController
  def show
    if params[:path].split('/').first == 'admin'
      layout = 'admin'
    else
      layout = 'application'
    end

    render "tests/#{params[:path]}", layout: layout
  end
end

これで、

http://localhost:3000/tests/blog/index
  -> /views/tests/blog/index.html.slim
http://localhost:3000/tests/blog/category/index
  -> /views/tests/blog/category/index.html.slim

http://localhost:3000/tests/admin/entries/index
  -> /views/tests/admin/entries/index.html.slim
http://localhost:3000/tests/admin/entries/edit
  -> /views/tests/admin/entries/edit.html.slim

のようにできるはず。

.slim なのは読み替えてください。

3
4
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
3
4