Rails route to model instance - by domain name

I have a Rails 3 app, say with hotels where the hotels are owned by parents. When the user clicks on the application (served by mongrel โ†’ nginx), I want the domain name used in the request to decide in which area of โ€‹โ€‹the hotels to serve (domain name area โ†’). For this, I see two options:


1) Rewrite the URL with nginx by inserting the area identifier after the domain name (for example, birminghamhotels.co.uk => proxy_pass http: // myupstream / areas / 3 $ REQUEST_URI).

Advantages: Domain to object mapping takes place where accepted domains are defined: nginx.conf. It should be transparent to users (quite a few URLs are possible as they correspond).

Disadvantages: Breaks Rails url helpers, no more than link_to or form_for. Linking to hard-coded objects is naughty.


2) Catch the domain name in routes.rb and view the Area using the unique "domain" attribute for each Region (or even has_many if you want).

Benefits: Allow all Rails URL Helpers to be used. The requested domain is associated directly with the resource, so you can handle exceptions.

Disadvantages: without rewriting URLs with nginx users will not see: birminghamhotels.co.uk/areas/3/hotels/42 instead of just birminghamhotels.co.uk/hotels/42? In addition, I do not know how to do it!


So, I tried option # 1, but ran into problems with URL helpers, etc. I tried to come up with a way to try option number 2, but could not understand the correct syntax, despite a lot of ogl. Now the fact that I canโ€™t find answers to the queries makes me think that I was wrong with this problem. Is there a third option? How would you decide?

Oh, and btw, I'm not building another website for publishing on the Internet - that's enough. It just turned out to be a fairly close example.

+2
ruby-on-rails nginx domain-name model routes
source share
1 answer

Assuming there is some domain_name field in each area, it looks like you should do something like this:

class HotelsController < ApplicationController def index @hotels = Area.find_by_domain_name(request.subdomains.first).hotels end end 

You can even reorganize it into named_scope using lambda if you want.

+1
source share

All Articles