Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - how to get find domain url in a layout

I had request.env['http_host'] working on localhost, but it causes an error when referenced in a layout page on heroku.

This request works in a view and displays the correct base url, but it causes an error when I move the code to the layout. Note - I'm using this to build absolute urls for images in html emails.

  <%= "#{request.env['HTTP_HOST']}/assets/email_header_image.png" %> 
  <%= image_tag "#{request.env['HTTP_HOST']}/assets/email_header_image.png" %>

error received:

ActionView::Template::Error (undefined method `env' for nil:NilClass):
like image 423
Bob Cavezza Avatar asked Mar 23 '12 17:03

Bob Cavezza


2 Answers

If you want the host without the port, just use:

request.host

edit: Oops, I've just noticed that you're using the code in the view. I don't know if it is visible over there, I've only used it in controllers, but that's fairly simple to overcome by setting an instance variable.

like image 134
Castilho Avatar answered Sep 23 '22 19:09

Castilho


  1. In your controller, set an instance variable equal to the host:
    • @host = request.host
  2. In your view, reference the instance variable using
    • <%= @host %>
like image 29
Marty Cortez Avatar answered Sep 23 '22 19:09

Marty Cortez