Dynamic Rails routing based on database

后端 未结 2 1497
梦谈多话
梦谈多话 2021-02-04 19:54

I\'m building a CMS with various modules (blog, calendar, etc.) using Rails 2.3. Each module is handled by a different controller and that works just fine.

The only prob

2条回答
  •  一整个雨季
    2021-02-04 20:14

    In Rails 3.2 this was what I came up with (still a middleware):

    class RootRewriter
      def initialize(app)
        @app = app
      end
    
      def call(env)
        if ['', '/'].include? env['PATH_INFO']
          default_thing = # Do your model lookup here to determine your default item
          env['PATH_INFO'] = # Assemble your new 'internal' path here (a string)
          # I found useful methods to be: ActiveModel::Naming.route_key() and to_param
        end
    
        @app.call(env)
      end
    end
    

    This tells Rails that the path is different from what was requested (the root path) so references to link_to_unless_current and the like still work well.

    Load the middleware in like so in an initialiser:

    MyApp::Application.config.middleware.use RootRewriter
    

提交回复
热议问题