Rails 3 路由和多个域 [英] Rails 3 routing and multiple domains

查看:25
本文介绍了Rails 3 路由和多个域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用允许人们创建投资组合.我希望他们能够将他们的域连接到他们的投资组合.

My app allows people to create portfolios. I would like for them to be able to connect their domain to their portfolio.

所以 somedomain.com 会显示/portfolio/12,someotherdomain.com 会显示/portfolio/13 等等.但我不想要重定向.我希望用户在浏览器 url 中看到 somedomain.com.

So somedomain.com would show /portfolio/12, someotherdomain.com would show /portfolio/13 and so on. But I don't want the redirect. I want the user to see somedomain.com in the browser url.

我该怎么做?

好的,我找到了这个解决方案:

Ok, I've found this solution:

match "/" => "portfolio#show", 
  :constraints => { :domain => "somedomain.com" }, 
  :defaults => { :id => '1' }

因为我没有很多自定义域,所以现在很好,但问题是 - 如何使这个动态,从数据库读取域和 ID 数据?

As I don't have many custom domains, this is fine for now but the question is - how to make this dynamic, to read domain and id data from db?

推荐答案

首先,您应该向投资组合模型添加一个字段来保存用户的域.确保该字段是唯一的.为数据库中的字段添加索引也是明智之举.

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.

其次,设置您的根以路由到 portfolios#show 操作,就像您已经做的那样,但没有限制.

Second, set your root to route to the portfolios#show action, as you already did, but without the constraints.

然后,在 PortfoliosController#show 方法中,执行以下检查:

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

此后,唯一要做的就是确保您自己的域不会触发 portfolio#show 操作.这可以使用您之前使用的约束来完成,但现在使用您自己的域.请务必将此行放在 routes.rb 中 portfolio#show 操作行上方,因为优先级基于创建顺序.

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.

这篇关于Rails 3 路由和多个域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆