How to set root_url

2020-02-26 04:35发布

问题:

In my Ruby on Rails 3.1 app I have a link like this:

<%= link_to 'Home', root_url %>

On My dev. machine it renders a link with "localhost:3000". On production it renders a link with an IP Address like this "83.112.12.27:8080". I would like to force rails to render the domain address instead of the IP Address. How can I set root_url?

回答1:

In your routes set:

 root :to => 'welcome#index'

and in your links set:

<%=link_to "Home", root_path %>

It will render

<a href="/">Home</a>

So in your localhost It'd take you to

http://localhost:3000/

and in your production server It'd take you to

http://yourdomian.com/

and the routes.rb will render the index action of the controller welcome by default.

PS. you also need to remove index.html from public directory in order to use this.


UPDATE

A little bit more on routing:

Rails Routing from the Outside In



回答2:

You are looking for ActionController's default url option. So you can do something like:

class ApplicationController < ActionController::Base
  def default_url_options
    if Rails.env.production?
      {:host => "www.example.com"}
    else  
      {}
    end
  end
end

This also works for ActionMailer. As well, both can be set in your environment .rb or application.rb

# default host for mailer
config.action_mailer.default_url_options = {
  host: 'example.com', protocol: 'https://'
}

# default host for controllers
config.action_controller.default_url_options = {
  :host => "www.example.com"
}


回答3:

Perhaps you could just do something like this in your ApplicationController:

class ApplicationController < ActionController::Base
  helper_method :home_uri

  def home_uri
    Rails.env.production? ? 'http://www.yourdomain.com' : root_url
  end
  ...
end

And then change your link to be like this: <%= link_to 'Home', home_uri %>

This makes a helper method, home_uri, which returns the url you desired if the application is being run in the development environment. I don't think that you can easily overwrite root_url, and I also think it's likely a bad idea. I had the helper method end with uri instead of url because rails uses the router to automatically create methods that end with url, so if you had a route named home, this solution won't overwrite or conflict with that named route helper method. You can read more about named route helper methods here if you're interested.