【发布时间】:2014-04-23 11:59:07
【问题描述】:
我们创建了一个包含多个站点的多租户应用程序,每个站点都可以从后端修改路由。
在 routes.rb 中,我们为所有站点加载动态路由并将它们放入这样的主机约束中
routes.rb
Frontend::Application.routes.draw do
DynamicRoutes.load
end
app/models/dynamic_routes.rb
class DynamicRoutes
# dynamically loads the routes from settings into the routes.rb file
# and adds a host constraint to just match with the current sites host
# http://codeconnoisseur.org/ramblings/creating-dynamic-routes-at-runtime-in-rails-4
def self.load
if Site.table_exists?
Frontend::Application.routes.draw do
Site.includes(:setting).each do |site|
site.routes.each do |route|
# write the route with the host constraint
constraints(:host => site.hostname) do
case route[0]
when :shop_show
match "#{route[1]}", to: 'shops#show', via: [:get], as: "shop_show_#{site.id}"
end
end
end
end
end
end
end
# allows to reload the routing
# e.g. when changes in route settings where made
#
def self.reload
Rails.application.reload_routes!
end
end
因此,我们为每个站点创建所有路由,并将它们与主机约束相匹配。除非我们使用 url_for 帮助程序
,否则这工作正常@site = Site.find_by(hostname: request.host)
url_for controller: 'shop', action: 'show', host: @site.hostname
url_for 返回第一个匹配的 url,不管它应该属于哪个主机。所以不使用主机约束,即使我放了一个主机:param
您知道如何将 url_for 与主机约束一起使用吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 routing