Using Helpers inside a Controller

I want to use helpers inside a controller method for an AJAX
application. After the page is loaded and displayed, there will be an
asynchronous javascript request to load additional resources such as
html forms and other data.

The controller which handles the request will collect the resources and
send them back in json format.

def get_resources

data=Hash.new
data[:form1]=form_helper1()
data[:form2]=form_helper2()
…etc…

render :text data.to_json, :layout=>false
end

This works great if I’m loading up the data hash with pure data, but I
can’t collect html elements such as forms that require helpers because I
can’t call the helper inside of the controller.

I searched the web for a workaround and came across code to be defined
insider your controller:

def help
Helper.instance
end

class Helper
include Singleton
include ActionView::Helpers::MyHelper
end

But no dice. I get an uninitialized constant error for
ActionView::Helpers::MyHelper. If I instead include just MyHelper, then
rails complains that the helpers that are used inside MyHelper are now
undefined.

I really don’t want to construct the forms inside my controller, but
that’s what I’m going to have to do if I can’t figure out how to call my
helpers.

Any thoughts?

On 7/14/07, J. Sorenosn [email protected] wrote:

can’t call the helper inside of the controller.

If I am understanding you correctly, that means you want your AJAX
request to return HTML markup instead of data, right? If so, you
should really use a view component like a partial, which can itself
use helpers just fine. In the second edition of Agile Web D.
With Rails, Chapter 9 (“Task D: Add a Dash of AJAX”) has an example
of this technique.

Controllers should be about executing business logic and providing
data to the view, not being the view themselves. Helpers are view
helpers not controller helpers.

Craig McClanahan

class Helper
include Singleton
include ActionView::Helpers::MyHelper
end

But no dice. I get an uninitialized constant error for
ActionView::Helpers::MyHelper. If I instead include just MyHelper, then
rails complains that the helpers that are used inside MyHelper are now
undefined.

i had a certain controller and i added a helper with no probs, like
below: ( i had the following files:)

…/helpers/my_helper.rhtml # class MyHelper
…/controllers/example_controller.rhtml # class ExampleController

and then in example_controller.rhtml i did this:

require ‘my_helper’ #LOOK HERE

class ExampleController

include MyHelper #AND HERE