17

i know that doing

url_for(:only_path => false, :controller => 'home')

I will get, for example, http://localhost/home

But how do i handle to genereate http://localhost

4 Answers 4

14

This is an old question, but it still ranks high in searches. Currently, use root_url.

e.g.

<%= link_to "fully qualified root", root_url %>

will generate

<a href="http://www.example.com/">fully qualified root</a>
12

to get http://localhost, you'll simply:

<%= link_to "Home", root_path %>

That'll generate: <a href="/">Home</a> which will effectively link to http://localhost

1
  • 3
    To be clear, root_path maps to "/" while root_url maps to the absolute root URL (e.g. "http:// localhost:3000/")
    – user456584
    Commented Sep 30, 2014 at 16:31
11

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.

# 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'))
2

You can also use: ActionController::Base.relative_url_root

i.e. #{ActionController::Base.relative_url_root}/images/my_img.jpg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.