Ruby-on-rails rails 获取应用根目录/基本 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21321687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails get app root/base url
提问by Bruce Xinda Lin
In my app I have a few APIs that under api domain. Now in one of the API I want to generate a url that pointing to the main domain, say
在我的应用程序中,我在 api 域下有一些 API。现在在其中一个 API 中,我想生成一个指向主域的 url,例如
test.com/blabla...
I tried to use url_forbut seems the default root_urlor request.hostis in api domain. Url_for will make it to be
我尝试使用 url_for但似乎默认root_url或request.host在 api 域中。Url_for 将使它成为
api.test.com/blabla..
while I want it to be
虽然我希望它是
test.com/blabla...
Url_for can take a parameter
url_for 可以带一个参数
host: ...
to set it to be test.com/, the question is how can I get the root/base url (test.com) for host? root_urlor request.hostare all api.test.com.
将其设置为 test.com/,问题是如何获取主机的根/基本 url (test.com)? root_url或request.host都是 api.test.com。
Any ideas? Thanks.
有任何想法吗?谢谢。
回答by Caffeine Coder
Just so that it's useful to someone else , i came across this today
只是为了对其他人有用,我今天遇到了这个
request.base_url
gives the full path in local as well as on live .
提供本地和 live 的完整路径。
request.domain
gives just the domain name so it sometimes kinda breaks the link while redirecting
仅提供域名,因此有时在重定向时会断开链接
回答by Kaleem Ullah
Simplest alternative method:
最简单的替代方法:
include in you're class
包括在你的班级
include Rails.application.routes.url_helpers
create function or just use root_urlto get app root/base url:
创建函数或仅用于root_url获取应用程序根/基本 URL:
def add_host_prefix(url)
URI.join(root_url, url).to_s
end
finally: add
最后:添加
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
in:
在:
Your_project_root_deir/config/environments/development.rb
Your_project_root_deir/config/environments/development.rb
although helpers can be accessible only in views but this is working solution.
虽然助手只能在视图中访问,但这是可行的解决方案。
回答by Mitesh Sharma
request.domain fails on CF it given domain url not base url
request.domain 在 CF 上失败,因为域 url 不是基本 url

