动态网址-> Rails中路线的控制器映射 [英] Dynamic URL -> Controller mapping for routes in Rails

查看:70
本文介绍了动态网址-> Rails中路线的控制器映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够根据数据库中的信息将URL动态映射到Controller.

I would like to be able to map URLs to Controllers dynamically based on information in my database.

我正在寻找功能上与此等效的东西(假设为View模型):

I'm looking to do something functionally equivalent to this (assuming a View model):

map.route '/:view_name',
    :controller => lambda { View.find_by_name(params[:view_name]).controller }

其他人建议动态重建路线,但这对我不起作用,因为可能有成千上万的视图映射到同一控制器

Others have suggested dynamically rebuilding the routes, but this won't work for me as there may be thousands of Views that map to the same Controller

推荐答案

这个问题很旧,但是我发现它很有趣.可以使用路由器路由到Rack端点的功能在Rails 3中创建一个完整的解决方案.

This question is old, but I found it interesting. A fully working solution can be created in Rails 3 using router's capability to route to a Rack endpoint.

创建以下Rack类:

    class MyRouter
      def call(env)
        # Matched from routes, you can access all matched parameters
        view_name= env['action_dispatch.request.path_parameters'][:view_name]

        # Compute these the way you like, possibly using view_name
        controller= 'post' 
        my_action= 'show'

        controller_class= (controller + '_controller').camelize.constantize
        controller_class.action(my_action.to_sym).call(env)
      end
    end

在路线中

    match '/:view_name', :to => MyRouter.new, :via => :get

http://guides.rubyonrails.org/获取的提示routing.html#routing-to-rack-applications ,其中说:出于好奇,'posts#index'实际上扩展到PostsController.action(:index),它返回一个有效的Rack应用程序."

Hint picked up from http://guides.rubyonrails.org/routing.html#routing-to-rack-applications which says "For the curious, 'posts#index' actually expands out to PostsController.action(:index), which returns a valid Rack application."

在Rails 3.2.13中测试过的变体.

A variant tested in Rails 3.2.13.

这篇关于动态网址-> Rails中路线的控制器映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆