Render partial from helper_method

Msencenb picture Msencenb · Sep 3, 2011 · Viewed 7.7k times · Source

Ok so I have a helper method in the application controller:

def run_test(test_name)
  #computation stuff
  render :partial => test_name
end

And I call it like so in views:

<%= run_test("testpartial") %>

and it renders ok with only 1 (although... the render partial seems to be returning an array instead of just the partial content?), but if I put the run_test helper call in the view twice I get a double render error, which shouldn't be happening with partials.

Any ideas?

Answer

numbers1311407 picture numbers1311407 · Sep 3, 2011

render in a controller versus render in a view are different methods. The controller eventually calls render on a view, but the controller's render method itself expects to be called only once. It looks like this:

# Check for double render errors and set the content_type after rendering.
def render(*args) #:nodoc:
  raise ::AbstractController::DoubleRenderError if response_body
  super
  self.content_type ||= Mime[formats.first].to_s
  response_body
end

Note how it raises if called more than once?

When you call helper_method you give the view a proxy to the controller's version of render, which is not intended to be used in the same way as ActionView's, which is, unlike the controller's, expected to be called repeated to render partials and whatnot.