Rails 4 match all routes for one controller

2019-09-11 06:39发布

I have a controller with a number of static pages and I would ideally like to route them all with a wildcard.

Is it possible to do something like the following?

get 'static/:action'

3条回答
可以哭但决不认输i
2楼-- · 2019-09-11 07:00

You probably need something like get 'static/:action', to: 'static#show' and then in your StaticController show action render the correct static page based on the params[:action] parameter.

See http://guides.rubyonrails.org/routing.html#defining-defaults for more.

查看更多
Animai°情兽
3楼-- · 2019-09-11 07:08

You can route something like

get '*path', to: 'static#show'
查看更多
祖国的老花朵
4楼-- · 2019-09-11 07:22

Why don't you just use the show action:

#config/routes.rb
resources :static, param: :page, only: :show #-> url.com/static/:page

#app/controllers/static_controller.rb
class StaticController < ApplicationController
   def show
      render "#{params[:page]}"
   end
end

This way, you can pass the "page" directly through the link and have it all handled by Rails:

 <%= link_to "About", static_path("page") %>
查看更多
登录 后发表回答