动态网址 ->Rails 中路由的控制器映射 [英] Dynamic URL -> Controller mapping for routes in Rails
问题描述
我希望能够根据我的数据库中的信息动态地将 URL 映射到控制器.
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
推荐答案
这个问题很老了,但我发现它很有趣.可以在 Rails 3 中使用路由器的功能来创建一个完整的解决方案来路由到 Rack 端点.
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 类:
Create the following Rack class:
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屋!