Rails子域路由,资源不按预期工作

时间:2012-10-13 19:58:55

标签: ruby-on-rails ruby-on-rails-3 routes ruby-on-rails-3.2 subdomain

在标准博客应用中,我已将此路线添加到现有路线中:

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有效。

那么如何告诉我的博客资源成员操作他们应该在子域下路由而没有额外的冗余/ blogs::id?我真的需要手动完成这个吗? 我觉得我错过了什么。

1 个答案:

答案 0 :(得分: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