6

I am trying to get link_to to work when rendering a view outside of a controller. I've tried a couple different solutions found on the internet. You can see one attempt commented out.

It keeps resulting in: undefined method `host' for nil:NilClass

    ac = ApplicationController.new
    ac.class.include Rails.application.routes.url_helpers

    #context = Rails.configuration.paths['app/views']
    #view = ActionView::Base.new(context)
    #view.class.include Rails.application.routes.url_helpers
    #view.render :layout => 'layouts/pdf.html.haml', :template => 'reports/show.pdf.haml', locals: {alerts:@alerts}

    ac.render_to_string(:layout => 'layouts/pdf.html.haml', :template => 'reports/show.pdf.haml', locals: {alerts:@alerts})

I also tried over riding the class. None of the ActionView::Base stuff seems to work.

class ViewRenderer < ActionView::Base
  include Rails.application.routes.url_helpers
  include ApplicationHelper

  def default_url_options
     {host: Rails.application.routes.default_url_options[:host]}
  end
end
Natus Drew
  • 1,876
  • 1
  • 21
  • 23
  • 1
    I ended up having to extend the helpers into an instance of ActionView::Base – Natus Drew May 07 '15 at 01:40
  • 1
    Can you elaborate? I'm trying to render a partial (that contains `link_to`) to a string and getting the error: `ActionView::Template::Error: arguments passed to url_for can't be handled. Please require routes or provide your own implementation` – eggie5 Oct 08 '15 at 21:20

2 Answers2

1

Although this question is 4 years old, I answered a similar question that I thought could help here.

One option is to include the URL helpers directly in the locals passed to the template:

ac.render_to_string(
  layout: 'layouts/pdf.html.haml',
  template: 'reports/show.pdf.haml',
  locals: {url: Rails.application.routes.url_helpers, alerts: @alerts}
)

And then inside of your template you can call them with the host explicitly set:

url.user_url(host: 'www.mysite.com')

Or you can configure the host globally for your entire app:

# config/environments/development.rb
Rails.application.routes.default_url_options[:host] = 'www.mysite.com'
calebkm
  • 1,013
  • 4
  • 17
1

In Rails 5 you can just use ApplicationController.render:

ApplicationController.render(layout: 'layouts/pdf.html.haml', template: 'reports/show.pdf.haml', locals: {alerts: @alerts})

See also this comment on GitHub.

idmean
  • 14,540
  • 9
  • 54
  • 83