检测控制器中的基本网址? [英] Detect base url in controller?
问题描述
我们如何检测控制器中的根/基地址?
How can we detect the root / base url in the controller?
我正在运行一个函数,它需要知道在完成后将用户返回到哪里,我希望它能够在开发和生产中工作.目前,如果我只是使用域名,那么在开发中它会将用户返回到实际网站(即 www.example.com/reauth,而不是 http://localhost:3000),这是不可取的(在 dev 中,用户应该返回到 dev;它们不应该被链接到网站的生产版本).
I'm running a function that needs to know where to return the user to after it's finished, and I would like it to work in dev and prod. Presently, if I simply use the domain name, then in development it returns the user to the actual website (i.e. www.example.com/reauth, rather than http://localhost:3000), which isn't desirable (in dev, the user should be returned to dev; they shouldn't be linked to the prod version of the site).
所以我想要返回的代码:
So I want code that returns:
https://www.example.com
生产中和http://localhost:3000
开发中
https://www.example.com
in production andhttp://localhost:3000
in development
这是我需要将 refresh_url
的值设置为:
Here's a simplified version of the exact example I need the value for refresh_url
set to:
https://www.example.com/reauth
正在生产中,localhost:3000/reauth
开发中
https://www.example.com/reauth
in production and,localhost:3000/reauth
in development
注意这里的关键是url的后半部分是相同的,但第一部分(base url)是生产中的实际域,开发中的 localhost.
Note the critical thing here is that the latter part of the url is the same, but the first part (base url) is the actual domain in production, and localhost in development.
Stripe::AccountLink.create({
refresh_url: 'https://www.example.com/reauth'
})
目前我所知道的
我看过:
- 如何检测模型中的基本网址(以及在视图中),以及
- 如何获取基本网址(返回
NameError: undefined local variable or method 'request' formain:Object
)
- how to detect the base url in the model (and in the view), as well as
- how to get the base url (which returns
NameError: undefined local variable or method 'request' for main:Object
)
推荐答案
我发现此处的方法有效.
即
request.base_url
注意事项:
- 这将返回没有尾随正斜杠的网址.
- 这在 rails 控制台中不起作用
为了将来参考,以下是我解决的问题,根据应用程序是在 dev 还是 prod 中运行,给出正确的基本 URL:
For future reference, here's what solved for me to give the correct base url depending on whether the app's being run in dev or prod:
base_url = (!Rails.const_defined? 'Console') ? (request.base_url) : "http://localhost:3000"
这篇关于检测控制器中的基本网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!