【问题标题】:Custom route constraint not working in Rails 4自定义路由约束在 Rails 4 中不起作用
【发布时间】:2013-07-28 18:28:35
【问题描述】:

我无法让我的路由约束在 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

约束也没有出现在输出中...

请问我做错了什么?

【问题讨论】:

    标签: ruby-on-rails routes constraints subdomain


    【解决方案1】:

    我认为您可能需要使用约束类的实例,您必须调用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-16
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多