6

我正在尝试根据Ryan Bates 在 subdomains 上的截屏视频在 Rails 3 中设置子域。但是它对我不起作用。我有以下设置:

# routes.rb
constraints(Subdomain) do
  get 'devices' => 'devices#all'
end

# lib/subdomain.rb
class Subdomain
  def self.matches?(request)
    # binding.pry
    request.subdomain.present? && request.subdomain == "admin"
  end
end

加载 urladmin.localhost:3000/devices应该将我路由到devices#all,但是我收到路由错误Routing Error No route matches [GET] "/devices"显然我的路由不起作用。

我在上面的注释设置了一个pry调试会话,它被命中,所以我的约束正在工作,但我得到以下输出:

[1] pry(Subdomain)> request.subdomain
=> ""
[2] pry(Subdomain)> request.subdomains
=> []
[3] pry(Subdomain)> request.host
=> "admin.localhost"

因此,rails 没有获取 url 的管理部分并将其放入子域变量中。虽然我可以轻松地使用主机值来过滤到管理路由,但我想保持干净和正确。

为什么 rails 没有设置子域值?


编辑

jdoe和coreyward的答案都是正确的。让我失望的是,我也在使用powxip.io访问该网站并遇到同样的错误。这很奇怪,因为http://admin.app_name.192.168.1.68.xip.io/devicestld > 1。发生的事情是 was 的子域xipadmin.app_name.192.168.1.68考虑到匹配逻辑,它也会失败并且不会路由。

4

2 回答 2

12

因为 Rails 认为没有子域。

Rails expects you to provide a Top-Level Domain (TLD) length for TLDs with more than 1 dot. For example, if you had bbc.co.uk it would pickup "bbc" as the subdomain unless you specified the TLD length is 2, in which case the subdomain would be blank:

request.subdomain(2) #=> ""

This is also why you're seeing subdomains return an empty array: the last two segments are being discarded automatically. You could specify 0 as the TLD length to get back "admin", but that code will break in production with a real domain name, so I don't recommend it.

I recommend using a domain like admin.yourapp.dev that is routed back to your computer via localhost to make your app properly detect a subdomain. Just edit /etc/hosts to do it simply.

If you're curious, here is the Rails source for the subdomain method.

于 2012-06-15T19:10:27.890 回答
7

尝试使用特殊地址:http ://admin.lvh.me:3000/devices

或设置:

config.action_dispatch.tld_length = 0

在你的 development.rb 中并重新启动你的应用程序。

于 2012-06-15T19:10:08.850 回答