Alex Rivera | Logout

RubyOnRails: url_for application root

Asked 2010-10-07T15:40:19.153
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

Edit
Report

1 Answer

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'))
answered 2010-10-07T16:00:21.327

Your Answer