在route.rb中的Rails访问请求以获取动态路由 [英] Rails access request in routes.rb for dynamic routes
问题描述
我们的网站应允许显示与给定URL相关的不同内容..诸如wordpress中的多站点,其中我们有一个安装并根据URL提供内容。
Our websites should allow to show different contents related to the given url .. something like a multisite in wordpress where we have one installation and serve the content according to the url.
因为必须以正确的语言显示路线,所以我想使用动态路线方法来投放正确的内容。现在的问题是,如果动态的话,我找不到在route.rb中提供正确路线的方法。
as it is necessary to have the routes in the correct language I want to use a "dynamic route" approach to serve the right content. My problem is now that I dont find a way how to serve the proper routes in routes.rb if they are dynamic.
如何访问或传递 请求对象到routes.rb文件内的任何方法中
How can I "access" or "pass" the request object into any method inside the routes.rb file
fe像这样
Frontend::Application.routes.draw do
DynamicRouter.load request
end
app / models / dynamic_router .rb
app/models/dynamic_router.rb
class DynamicRouter
def self.load request
current_site = Site.find_by_host(request.host)
Frontend::Application.routes.draw do
current_site.routes do |route|
get "#{route.match}", to: "#{route.to}"
end
end
end
end
此操作无效,因为在route.rb中未定义请求。
this doesnt work because request is undefined in routes.rb
推荐答案
一种可行的解决方案是在route.rb上创建默认规则,并添加一个可以根据域转换路径的机架中间件
A possible soluction is to create the default rules on routes.rb and add a rack middleware that can transform a path according to the domain
# routes.rb
get '/category/:id', :to => 'categories#show'
在中间件中,您可以将 categoria /:id之类的路径转换为如果应用程序访问路由器层之前域与 .es匹配,则为 / category /:id。
In the middleware you can transform a path like 'categoria/:id' to '/category/:id' if the domain matches '.es', before the application hits the router layer.
有关机架中间件的更多信息: http://guides.rubyonrails.org/rails_on_rack.html
More on rack middleware: http://guides.rubyonrails.org/rails_on_rack.html
这篇关于在route.rb中的Rails访问请求以获取动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!