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:
1 | @controller.public_method |
To call a private method you can do this:
1 | @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 »
Jeremy Weiskotten
July 10, 2009
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
July 10, 2009
Can you just do this?
helper_method :public_method_name
This makes your controller method a helper method as well.
Ennuyer.net » Blog Archive » Rails Reading backlog
July 11, 2009
[...] Ruby on Rails: Accessing Controller Methods from Your View [...]
Mike
January 27, 2010
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.
Leave a comment