rails get app root/base url

a 夏天 提交于 2019-12-04 08:49:40

问题


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

test.com/blabla...

I tried to use url_for but seems the default root_url or request.host is in api domain. Url_for will make it to be

api.test.com/blabla..

while I want it to be

test.com/blabla...

Url_for can take a parameter

host: ...

to set it to be test.com/, the question is how can I get the root/base url (test.com) for host? root_url or request.host are all api.test.com.

Any ideas? Thanks.


回答1:


According to this you can do request.domain




回答2:


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 .

request.domain

gives just the domain name so it sometimes kinda breaks the link while redirecting




回答3:


Simplest alternative method:

include in you're class

include Rails.application.routes.url_helpers

create function or just use root_url to get app root/base 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

although helpers can be accessible only in views but this is working solution.




回答4:


request.domain fails on CF it given domain url not base url



来源:https://stackoverflow.com/questions/21321687/rails-get-app-root-base-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!