2013-01-24 4 views
1

저는 현재 내 응용 프로그램에서 사용중인 일부 범위 접두사를 제거하려고합니다. 내 경로는 다음과 같이 순간 (간단한 예을)에서레일 : 요청 기반 (& 데이터베이스 기반) 라우팅

:

예를 들어 이러한 경로 생성
scope 'p' 
    get ':product_slug', as: :product 
end 
scope 't' do 
    get ':text_slug', as: :text 
end 

:

/p/car 
/t/hello-world 

가 지금은 접두사없이 작동하는 경로를 원하는을 편지 (p & t). 그래서 (BTW 좋은 작품) 기존 데이터베이스 항목에 슬러그을 제한 :

text_slugs = Text.all.map(&:slug) 
get ':text_slug', as: :text, text_slug: Regexp.new("(#{text_slugs.join('|')})" 

product_slugs = Product.all.map(&:slug) 
get ':product_slug', as: :product, product_slug: Regexp.new("(#{product_slugs.join('|')})" 

문제 :

이 누군가의 text_slug 다른 사람의 product_slug이 될 수 있다는 것을 의미 멀티 테넌트 (multi-tenant) 응용 프로그램입니다 그 반대. 그래서 현재 사이트 (도메인 별)에서 슬러그를 필터링해야합니다.

text_slugs = Site.find_by_domain(request.host).texts.all.map(&:slug) 
get ':text_slug', as: :text, text_slug: Regexp.new("(#{text_slugs.join('|')})" 

그러나 요청가 routes.rb에서 사용할 수 없습니다 내가 노력 나는 모든 작동하지 않습니다

해결책은 다음과 같을 것입니다.

req = Rack::Request.new(env) 
req.host 

는 정말 많이 시도에 대한 감사드립니다 : 요청 : 랙에

직접 호출 그렇지 않으면이 일할 수있는, Application.routes에 존재하지 않는 것 올바른 ENV 변수를 필요 어떤 힌트!

답변

1

http://guides.rubyonrails.org/routing.html#advanced-constraints에 대한 고급 제한 조건을 사용할 수 있습니다.

class SlugConstraint 
    def initialize(type) 
    @type = type 
    end 
    def matches?(request) 
    # Find users subdomain and look for matching text_slugs - return true or false 
    end 
end 

App::Application.routes.draw do 
    match :product_slug => "products#index", :constraints => SlugConstraint.new(:product) 
    match :tag_slug => "tags#index", :constraints => SlugConstraint.new(:tag) 
end 

은 BTW - 많이 ...

+0

덕분에 당신은 시험 문제로 실행할 수 있습니다,하지만 그건 또 다른 문제, 그것은 위대한 작품! _advanced constraints_를 사용해 보았지만 도메인 쿼리와 슬러그에 대한 전달 된 요청 정보를 사용하지 못했습니다. – Railsana

+0

@the future me : 초기화 프로그램 폴더에서 파일을 편집 할 때 앱을 다시 시작하십시오. – Railsana