RubyOnRails:url_for 应用程序根
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3883349/
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
RubyOnRails: url_for application root
提问by bonfo
i know that doing
我知道这样做
url_for(:only_path => false, :controller => 'home')
I will get, for example, http://localhost/home
例如,我会得到http://localhost/home
But how do i handle to genereate http://localhost
但是我如何处理以生成http://localhost
回答by Jesse Wolgamott
to get http://localhost, you'll simply:
要获取http://localhost,您只需:
<%= link_to "Home", root_path %>
That'll generate: <a href="/">Home</a>which will effectively link to http://localhost
这将生成:<a href="/">Home</a>这将有效地链接到http://localhost
回答by metkat
This is an old question, but it still ranks high in searches. Currently, use root_url.
这是一个古老的问题,但它仍然在搜索中排名靠前。目前,使用 root_url。
e.g.
例如
<%= link_to "fully qualified root", root_url %>
will generate
会产生
<a href="http://www.example.com/">fully qualified root</a>
回答by Eric
Depending on what your goals are, there are a few ways to use the server name or base URL. For the general case of, "I just need a reliable base URL that I can use anywhere," I use the config method.
根据您的目标,有几种方法可以使用服务器名称或基本 URL。对于“我只需要一个可以在任何地方使用的可靠基本 URL”的一般情况,我使用 config 方法。
# via routes.rb
map.root :controller => "foo", :action => "bar"
# view/controller:
root_url # inflexible. root_url will only ever be one URL
# via request object
url_for("http://"+request.host) # not available in models
# via config file (see railscast 85)
# environment.rb
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]
# config/config.yml
development:
server_name: localhost:3000
production:
server_name: foo.com
# view/controller:
url_for(APP_CONFIG('server_name'))
回答by Francisco Olano
You can also use: ActionController::Base.relative_url_root
你也可以使用: ActionController::Base.relative_url_root
i.e. #{ActionController::Base.relative_url_root}/images/my_img.jpg
IE #{ActionController::Base.relative_url_root}/images/my_img.jpg

