rails_has_elegance
rails_has_elegance

Reputation: 1692

Rails Subdomain routing with resources not working as expected

In a standard blog app I have added this route to my existing routes:

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

And these were/are my already existing routes:

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

In my controller I do @blog = Blog.find(request.subdomain), just to make it simple I use the id. Later I would use the blogs slug or an extra domain attribute.

This works fine insofar that http://17.lvh.me:3000 will show blog 17. But my member actions aren't routed as expected. Being on a blog subdomain, I would expect http://8.lvh.me:3000/settings, but only http://17.lvh.me:3000/blogs/17/settings works.

So how can I tell my blog resource member actions that they should be routed under the subdomain without the extra redundant /blogs/:id? Do I really need to do this all manually? I feel like I'm missing something.

Upvotes: 2

Views: 831

Answers (1)

mccannf
mccannf

Reputation: 16659

Try this:

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

You will have to have Blog.find(request.subdomain) in each of the actions in the controller.

P.S. I know this is a good theoretical exercise in using subdomains in Rails, but I personally prefer clean URLs.

Upvotes: 1

Related Questions