检测控制器中的基本网址? [英] Detect base url in controller?

查看:40
本文介绍了检测控制器中的基本网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何检测控制器中的根/基地址?

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 and
  • http://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'
  })

目前我所知道的

我看过:

  • 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屋!

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