Ruby on Rails: Accessing Controller Methods from Your View

by Charles Max Wood on July 7, 2009

I’ve recently seen several requests come through from people trying to figure out how to call controller methods from their views. The answer is pretty simple. Your controller instance, which is calling your view is stored in the instance variable @controller. So, calling public methods is as simple as this:

@controller.public_method

To call a private method you can do this:

@controller.send("private_method", args)

You should note that if you’re calling controller methods frequently in your views, you should consider putting them into helpers to make them available that way. If you need to manipulate or manage some data, the controller is the place to access the models for this, not the views.

{ 4 comments… read them below or add one }

Jeremy Weiskotten July 10, 2009 at 1:14 pm

A better way, IMO, is to call #helper_method in your controller to declare any methods as “helpers” for use in views:

helper_method :my_helper

Reply

Leon July 10, 2009 at 4:15 pm

Can you just do this?

helper_method :public_method_name

This makes your controller method a helper method as well.

Reply

Mike January 27, 2010 at 1:34 am

Leon has clearly got the cleanest solution.
All your helper methods are available in your views already, but if you need to declare some methods in the controller as helper_methods, this works beautifully.

Reply

Jason June 14, 2010 at 5:35 am

but if you put into helper, you can’t access to request object.

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: