Last Updated: February 25, 2016
·
2.884K
· dcdieci

Render view outside of a controller in Rails 4

Apparently this has been an old issue in rails and there are many solutions like

ApplicationController.new.render_to_string( [...] )

but this was not working in my case since I wanted to use locals and a model.
So I tried

 def render_anywhere(partial, assigns= {})
view = ActionView::Base.new(Rails.configuration.paths['app/views'], assigns)
view.extend ApplicationHelper

end

which was also not working since it was not able to render urls in the view which.

So finally I stumbled upon this issue here
https://github.com/rails/rails/issues/11662
and adding

view.class_eval do
  include Rails.application.routes.url_helpers
  include ApplicationHelper
  def protect_against_forgery?
    false
  end
end

solved the problem.