Rails - how to get search engine url in layout

I had request.env['http_host'] working on localhost, but it causes an error when linking to the hero page on the layout page.

This request works in the view and displays the correct base url, but it causes an error when moving the code to the layout. Note. I use this to create 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" %> 

received error:

 ActionView::Template::Error (undefined method `env' for nil:NilClass): 
+7
source share
2 answers

If you need a host without a port, just use:

 request.host 

edit: Oh, I just noticed that you are using code in a view. I do not know if this is visible there, I used it only in controllers, but it is quite simple to overcome it by setting the instance variable.

+15
source
  • In your controller, set the instance variable equal to the host:
    • @host = request.host
  • In your view, reference an instance variable using
    • <%= @host %>
+5
source

All Articles