自定义路由约束在Rails 4中不起作用

时间:2013-07-28 18:28:35

标签: ruby-on-rails routes constraints subdomain

我无法让我的路由约束在Rails 4中工作。这是我的路由文件:

Catapult::Application.routes.draw do
  constraints Subdomain do
    resources :contacts do
      member do
        get 'delete'
      end
    end
  end
end

这是子域约束:

class Subdomain
  def self.matches?(request)
    p request.subdomains.first # This never appears in the logs
    request.subdomains.first !~ /www|catapultcentral|customercube|lvh/
  end
end

如上面的代码中所述,p语句的输出永远不会出现在日志中 似乎永远不会应用约束。这是rake routes

的输出
        Prefix Verb   URI Pattern                    Controller#Action
delete_contact GET    /contacts/:id/delete(.:format) contacts#delete
      contacts GET    /contacts(.:format)            contacts#index
               POST   /contacts(.:format)            contacts#create
   new_contact GET    /contacts/new(.:format)        contacts#new
  edit_contact GET    /contacts/:id/edit(.:format)   contacts#edit
       contact GET    /contacts/:id(.:format)        contacts#show
               PATCH  /contacts/:id(.:format)        contacts#update
               PUT    /contacts/:id(.:format)        contacts#update
               DELETE /contacts/:id(.:format)        contacts#destroy

约束不会出现在输出中......

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为您可能需要使用约束类的实例,您必须调用Subdomain.new:

Catapult::Application.routes.draw do
  constraints Subdomain.new do
    resources :contacts do
      member do
        get 'delete'
      end
    end
  end
end

这意味着matches?不应该是类方法,而应该是实例方法:

class Subdomain
  def matches?(request)
    request.subdomains.first !~ /www|catapultcentral|customercube|lvh/
  end
end