Wednesday 5 June 2013

Gotcha: undefined method `render' for SomeTemplate

I recently had to scratch my head over a strange exception message I'd never seen before:

undefined method `render' for #<SomeTemplate:0xb17da594>

The problem was, it came with *no* application trace at all... just the usual Rails stack-trace.

I had to guess at where the problem came from by grepping for SomeTemplate in the controller-action that had exploded, and came across the following line of code:

  @template = SomeTemplate.new(params[:some_template])

Now SomeTemplate is a model of ours, and prior to this error occurring that line of code had been:

  @temp = SomeTemplate.new(params[:some_template])

I have a strong aversion to calling any variable "temp", because my reaction to seeing a variable called temp is to say "a temporary what?" not "oh, that's an instance of a template", and if I'm getting the wrong idea when I look at a variable name - that's an indication it should be changed.

So I renamed it...

Unfortunately, it turns out that @template is a magic variable in Rails that refers to the template to be rendered in a given controller action.

So Just Don't Do That.

The code has now been rewritten to the following, and works just fine:

  @some_template = SomeTemplate.new(params[:some_template])

2 comments:

Trung LE said...

Interesting find. However I don't think @temp is a good naming though, @tmpl seems a better choice

Taryn East said...

Yes, it was a bad variable name - that's why I wanted to refactor it :)