8

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?

Msencenb
  • 5,675
  • 11
  • 52
  • 84
  • Which versions of ruby and rails are you using, I don't get this behaviour when running 3.1? – Benoit Garret Sep 03 '11 at 00:40
  • 3.1. I was using an RC candidate but I upgraded just to be sure and it still isn't working. – Msencenb Sep 03 '11 at 01:42
  • Hmmm... So turns out I was defining this helper method in the application_controller using helper_method :run_test however moving it to application_helper file in the helpers folder works. So.. I have a whole in my understanding between the difference of a helper defined in the application controller and a helper defined in a helper file. Anyone able to fill me in? – Msencenb Sep 03 '11 at 01:50
  • 1
    A method in the application controller is only available to controllers. A method in a helper is only available to views. – drummondj Sep 03 '11 at 02:17
  • 1
    Thanks John. If you want to add that as an answer I'll gladly mark it as accepted for you :) – Msencenb Sep 03 '11 at 02:40

3 Answers3

9

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.

numbers1311407
  • 33,686
  • 9
  • 90
  • 92
5

Looks like in Rails 3.2 this just works:

# application_helper.rb
def render_my_partial
  render "my_partial"
end
fguillen
  • 36,125
  • 23
  • 149
  • 210
-2

You could try using render_to_string method in the view helper

render_to_string :partial => test_name, :layout => false
dexter
  • 13,365
  • 5
  • 39
  • 56