基于数据库的动态Rails路由

基于数据库的动态Rails路由

本文介绍了基于数据库的动态Rails路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Rails 2.3 构建具有各种模块(博客、日历等)的 CMS.每个模块都由不同的控制器处理,效果很好.

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.

我唯一的问题是根 URL.根据用户选择的配置,此默认 URL 应显示不同的模块,即不同的控制器,但我必须确定正确控制器的唯一方法是检查数据库中要显示的默认"模块.

The only problem I have is with the root URL. Depending on the configuration chosen by the user, this default URL should show a different module i.e. a different controller, but the only way I have to determine the correct controller is by checking the database for what "default" module is to be shown.

目前我正在使用一个特定的根"控制器,它检查数据库并重定向到正确的控制器.但是,我不希望更改 URL,这意味着我想从同一个请求中调用正确的控制器.

For the moment I'm using a specific "root" controller which checks the database and redirects to the correct controller. However I'd prefer the URL not to be changed, which means I want to invoke the correct controller from the very same request.

我尝试使用 Rails Metal 来获取此信息并手动调用我想要的控制器,但我想我可能会重新发明轮子(确定请求路径以选择控制器、管理会话等).

I've tried using Rails Metal to fetch this info and manually calling the controller I want but I'm thinking I may be reinventing the wheel (identify the request path to choose the controller, manage session, etc.).

有什么想法吗?非常感谢提前!

Any idea? Thanks a lot in advance!

推荐答案

这个问题可以通过一些Rack中间件来解决:

This problem can be solved with some Rack middleware:

lib/root_rewriter.rb 中的这段代码:

module DefV
  class RootRewriter
    def initialize(app)
      @app = app
    end

    def call(env)
      if env['REQUEST_URI'] == '/' # Root is requested!
        env['REQUEST_URI'] = Page.find_by_root(true).uri # for example /blog/
      end

      @app.call(env)
    end
  end
end

然后在你的 config/environment.rb 底部

require 'root_rewriter'
ActionController::Dispatcher.middleware.insert_after ActiveRecord::QueryCache, DefV::RootRewriter

此中间件将检查请求的页面 (REQUEST_URI) 是否为/",然后查找实际路径(具体实现取决于您 ;-)).您可能会在某处缓存此信息 (Cache.fetch('root_path') { Page.find... })

This middleware will check if the requested page (REQUEST_URI) is '/' and then do a lookup for the actual path (Implementation to this is up to you ;-)). You might do good on caching this info somewhere (Cache.fetch('root_path') { Page.find... })

检查 REQUEST_URI 时存在一些问题,因为并非所有网络服务器都能正确地传递它.有关 Rails 中的整个实现细节,请参阅 http://api.rubyonrails.org/classes/ActionController/Request.html#M000720(点击查看源代码")

There are some problems with checking REQUEST_URI, since not all webservers pass this correctly. For the whole implementation detail in Rails see http://api.rubyonrails.org/classes/ActionController/Request.html#M000720 (Click "View source")

这篇关于基于数据库的动态Rails路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:58