gpt4 book ai didi

ruby-on-rails - 动态 URL -> Rails 中路由的 Controller 映射

转载 作者:行者123 更新时间:2023-12-03 22:30:52 25 4
gpt4 key购买 nike

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

我希望做一些功能上与此等效的事情(假设是 View 模型):

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

其他人建议 dynamically rebuilding the routes ,但这对我不起作用,因为那里 可能是映射到同一个 Controller 的数千个 View

最佳答案

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

创建以下 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

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

提示来自 http://guides.rubyonrails.org/routing.html#routing-to-rack-applications上面写着“奇怪的是,'posts#index' 实际上扩展到 PostsController.action(:index),它返回一个有效的 Rack 应用程序。”

在 Rails 3.2.13 中测试的变体。

关于ruby-on-rails - 动态 URL -> Rails 中路由的 Controller 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2596312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com