Ruby on Rails: Accessing Controller Methods from Your View

by woody2shoes 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.

  • http://weiskotten.com Jeremy Weiskotten

    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

  • Leon

    Can you just do this?

    helper_method :public_method_name

    This makes your controller method a helper method as well.

  • Pingback: Ennuyer.net » Blog Archive » Rails Reading backlog

  • Mike

    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.

  • Jason

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

  • Pingback: Undenfined local variable or method when the view call a method - Programmers Goodies

  • Anonymous

    I can’t seem to get this to work?  I have a controller with 2 methods.  In the view corresponding to one of these methods I call “@controller.some_method”.  However, I get an NoMethodError.  ”undefined method ‘some_method’ for nilClass……………

    • http://teachmetocode.com Charles Max Wood

      What version of Rails are you using? I believe this was in Rails 2.3.x. May not work in Rails 3.x.

      • Anonymous

        3.1.2 I think. Fresh install on Saturday so whatever the latest version is. Don’t have my laptop to check at the moment.

Previous post:

Next post: