resources :singlepages get '/company', to:'singlepages#show', sid:1
###singelpage_controller.rb
1 2 3 4 5 6 7 8 9 10
classSinglepagesController < ApplicationController defindex @singlepages = Singlepage.order("sid DESC").page(params[:page]).per(5) @title = 'singlepage manage' end defshow @singlepage = Singlepage.find_by_sid(params[:sid]) redirect_to not_found_path unless @singlepage end end
###model/singlepage.rb
每次保存前重启路由器
1 2 3 4 5 6
classSinglepage < ActiveRecord::Base after_save :reload_routes defreload_routes DynamicRouter.reload end end
###model/dynamic_router.rb
动态路由,包括加载和重启
1 2 3 4 5 6 7 8 9 10 11 12 13
classDynamicRouter defself.load ComingSoon.application.routes.draw do Singlepage.all.each do|pg| puts "Routing #{pg.name}" get "/#{pg.name}", :to => "pages#show", defaults: { id: pg.id } end end end defself.reload ComingSoon.application.routes_reloader.reload! end end
###config/routes.rb
在路由配置文件里加载动态路由模块
1 2 3 4 5
Rails.application.routes.draw do root 'home#index' get 'not_found' => 'singlepages#not_found' DynamicRouter.load end