2

在一個標準的博客應用我加入這條路線我現有的航線有:Rails的子域的路由與資源工作不正常

match '', to: 'blogs#show', constraints: { subdomain: /.+/ } 

而這些人/是我的現有路線:

resources :blogs do 
    member { get :settings } 
    member { get :stats } 
    member { match ':year/:month/:day/:article_id', to: 'blogs#show_article', :constraints => { year: /\d{4}/, month: /\d{2}/, day: /\d{2}/ } } 
end 

在我的控制器中,我做了@blog = Blog.find(request.subdomain),只是爲了讓它更簡單我使用了id。之後我會使用博客slug或額外的域屬性。

這工作正常,只要http://17.lvh.me:3000將顯示博客17.但我的成員操作不按預期路由。作爲博客子域名,我期望http://8.lvh.me:3000/settings,但只有http://17.lvh.me:3000/blogs/17/settings有效。

那麼我怎麼能告訴我的博客資源成員的行動,他們應該被路由在子域下沒有額外的冗餘/博客/:ID?我真的需要手動完成嗎? 我覺得我失去了一些東西。

回答

1

試試這個:

scope '/' do 
with_options :conditions => {:subdomain => /.+/}, :controller => :blogs do |site| 
    site.match '', :action => :show 
    site.get '/settings', :action => :settings 
    site.get '/stats', :action => :stats 
    site.match ':year/:month/:day/:article_id', to: 'blogs#show_article', :constraints => { year: /\d{4}/, month: /\d{2}/, day: /\d{2}/ } 
end 
end 

您必須在每個控制器的行動Blog.find(request.subdomain)

P.S.我知道這是a good theoretical exercise in using subdomains in Rails,但我個人更喜歡clean URLs

+0

謝謝你的回答!我以某種方式無法讓它與我現有的路線一起工作。現在完全沒有子域名。稍後會處理它 –