How to do static content in Rails?

后端 未结 8 926
孤城傲影
孤城傲影 2020-11-30 17:47

Looking at different options:

One is to just put the static pages in the public/ folder, but I do want the header from layout/application to be consistent.

I

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 18:22

    I used the idea of a generalized controller from the answers given, but I wanted to catch 404s, so I put an action in it to handle either case:

    # app/controllers/static_controller.rb
    class StaticController < ApplicationController
        def static_or_404
            render params[:static]
        rescue ActionView::MissingTemplate
            render :not_found
        end
    end
    

    and then at the very bottom in my routing:

    # config/routes.rb
    get '*static', to: 'static#static_or_404'
    

    It serves the view from app/views/static of the same name as the path, and if there isn't such a view, it serves app/views/static/not_found.html.erb. One could also replace render :not_found with redirect_to root_path or anything else one wanted to have happen.

提交回复
热议问题