0

I migrated from rails 2.x to 3.x. Now when calling a controller method throws

undefined method `my_helper_method' for nil:NilClass

MyController.rb

class MyController < ApplicationController
    def foo
      @template.my_helper_method
    end
end

MyControllerHelper.rb

class MyControllerHelper
    def my_helper_method
      puts "Hello"
    end
end

ApplicationController

class ApplicationController < ActionController::Base
   helper :all
end

How to get this working?

Achaius
  • 5,904
  • 21
  • 65
  • 122

2 Answers2

3

This is actually answered in another SO post: Rails 3: @template variable inside controllers is nil

Essentially, you can replace @template with view_context

Community
  • 1
  • 1
Melinda Weathers
  • 2,649
  • 25
  • 31
1

@template is an object, in your case nil. If this object doesn't has the method (my_helper_method) in it, you cannot call it (especially not if it is nil).

Methods defined in helpers are called like regular methods. But not in controllers, they are called in views. Your helper :all just makes all helpers available to the views.

So, in your view: my_helper_method :arg1, :arg2

IF you need a method for your object (@template), you need to give your object this method.

Example:

class Template < ActiveRecord::Base

  def my_helper_method
    # do something on a template instance
  end

end


class MyController < ApplicationController
  def foo
    @template = Template.first
    @template.my_helper_method # which actually isn't a helper
  end
end

What helpers do:

module MyHelper
  def helper_method_for_template(what)
  end
end

# in your view
helper_method_for_template(@template)

Mixing in a helper (be aware of having a mess in your code when mixing view helpers with views and models)

class Template < ActiveRecord::Base
  include MyHelper

  # Now, there is @template.helper_method_for_template(what) in here. 
  # This can get messy when you are making your helpers available to your
  # views AND use them here. So why not just write the code in here where it belongs
  # and leave helpers to the views? 
end
pdu
  • 10,295
  • 4
  • 58
  • 95
  • But you are migrating to rails3. I don't know why it is working, but helpers are supposed to help in your views. If you want to include helpers in your controller, do `include MyControllerHelper` in your controller. However, these are still "usual" methods and not instance methods for an object ( e.g. `@template`). You could make them available for this object when mixing in the helper methods into your Model/Instance Base. But this would not really follow the convention. – pdu Jan 18 '12 at 10:29
  • you are better off `migrating` and not `patching-everything-so-the-old-things-which-are-not-good-are-still-working`. If you really want to do the second one, stay on rails 2.x. I updated the answer, have a look. What you want is to define those methods inside your Model or whatever `@template` is created of. – pdu Jan 18 '12 at 10:33