プロダクト開発日誌

技術のことなど

【Rails】固定ページの作成

Controllerを作成

touch app/controllers/pages_controller.rb

# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  def show
    render template: "pages/#{params[:page]}"
  end
end

ルートを作成

Rails.application.routes.draw do
  get "/:page": "pages#show"
end

viewの作成

mkdir app/views/pages
touch app/views/pages/about.html.erb
touch app/views/pages/company.html.erb
touch app/views/pages/privacy_policy.html.erb

404

# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  before_action :valid_page!

  def show
    render "pages/#{params[:page]}"
  end

  private

  def valid_page!
    unless File.exist?(Pathname.new(Rails.root + "app/views/pages/#{params[:page]}.html.slim"))
      render file: 'public/404.html', status: :not_found
    end
  end
end