My app allows people to create portfolios. I would like for them to be able to connect their domain to their portfolio.
So somedomain.com would show /portfolio/12,
The request
object seems not to be available to the routes.rb
file w/o some patching.
There are some plugins that make it available, but most of them seem to be outdated. This one here request_routing seems to be with the latest commit dates so it would be most up to date. Though I doubt it will work with Rails 3.0 out of the box, it is a start and might not be that hard to port.
Your users can set DNS CNAME redirects so that requests for theirdomain.com
land on your_app.com/portfolio/12
.
Ok, let's assume you own yourdomain.com
and use it as your home page for your application. And any other domain name like somedomain.net
is mapped to a portfolio page.
First of all, in your routes.rb
you need to catch yourdomain.com
and map it to wherever your home page is, so that it stands out from the rest of the crowd.
root :to => "static#home", :constraints => { :domain => "yourdomain.com" }
Then you need to catch any other root on any domain and forward it to your PortfoliosController
root :to => "portfolios#show"
Keep in mind that this line will only be checked if the previous line fails to match.
Then in your PortfoliosController
find the requested portfolio by its domain rather than id.
def show
@portfolio = Portfolio.find_by_domain(request.host)
…
end
Of course you may want to rescue from an ActiveRecord::RecordNotFound
exception in case the domain is not in your database, but let's leave that for another discussion.
Hope this helps.
First, you should add a field to the portfolio model to hold the user's domain. Make sure this field is unique. Adding an index to the field in your database would also be wise.
Second, set your root to route to the portfolios#show
action, as you already did, but without the constraints.
Then, in the PortfoliosController#show
method, do the following check:
if params[:id]
@portfolio = Portfolio.find(params[:id])
else
@portfolio = Portfolio.find_by_domain(request.host)
end
After this, the only thing left to do is to make sure your own domain does not trigger the portfolio#show
action. This can be done with the constraint you used before, but now with your own domain. Be sure to put this line in routes.rb above the line for the portfolio#show
action, since the priority is based upon order of creation.