【问题标题】:Rails 4 url_for with host constraintRails 4 url​​_for 与主机约束
【发布时间】: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


    【解决方案1】:

    我的应用程序中有相同的任务。 url_for 忽略主机参数。但是我们可以通过以下方式在 ApplicationController 中创建额外的路径助手:

    ApplicationController.rb

    %w( shop_show ).each do |helper|
      helper_name = "#{helper}_path".to_sym
      helper_method helper_name
      define_method(helper_name) { |*args| send "#{helper}_#{site.id}_path", *args }
    end
    

    之后,您可以在视图中使用通用路径 shop_show_path。当然,您应该根据您的主机/域动态分配 site 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多