Search code examples
ruby-on-railsroutessubdomain

Rails: simplest way to put a blog on a subdomain


I've been digging around on subdomains in Rails for a couple days and haven't found a good explanation of this yet...

I have a rails app which has a blog integrated into it, and I'd like to put that blog on a subdomain. Ie. blog.myapp.com.

Now, within the blog I want the user to be able to view posts, blog.myapp.com/posts/123. However, if the user were to click to any other resources on the site, say videos for example, I'd like them to be redirected back to root, ie. www.myapp.com/videos/123. I don't want blog.myapp.com/videos... to cause a routing error, I just want it to redirect.

Basically, I'm looking for the simplest way to setup a subdomain and specify that certain controllers use that subdomain and the others don't. Ideally I'd even like the controller layer to handle redirection both ways, so that in views I could link back and forth to things just using helpers like post_path(123) and video_path(123) and that the subdomain would automatically be used or not used based on which controller was serving the view.

I tried putting all the controllers in a constraints block, ie:

constraints :subdomain => 'www' do
    resources :sessions
    resources :users
    resources :videos
            root :to => 'home#show'
end

constraints :subdomain => 'nexturb' do
    resources :posts
    root :to => "posts#index"
end
root :to => 'home#show'

However this doesn't seem to work well, I've especially had trouble with getting redirection between links to work very consistently.

I'm pretty sure other people must have run into this issue in the past, but I can't seem to find a good example of this situation in writing. What's the best way to handle this?


Solution

  • With help from here, here, and here... I finally figured this out:

    constraints :subdomain => 'blog' do
        scope '', :subdomain => 'blog' do
            resources :posts
        end
        root :to => 'posts#index'
    end
    

    This causes the posts_path helper to correctly send visitors to the subdomain.