views:

32

answers:

2

Few questions:

  1. Is it possible to call a controller method in a helper module (e.g., application helper)?

  2. If so, how does the helper handle the rendering of views? Ignore it?

  3. In what instances would you want to call a controller method from a helper? Is it bad practice?

  4. Do you have any sample code where you're calling controller methods in helper?

A: 

Calling a controller from a helper violates the MVC pattern. IMO if you need to call a controller from a Rails view helper (like application_helper) then there is something about the design that could be improved. The intention is that helpers "help" views, and therefore only talk to models.

I'm not going to defend MVC itself here (there are a ton of references on the web), but this SO thread about calling the controller from a view should get you started.

http://stackoverflow.com/questions/1708015/calling-controller-from-view (note, this is an ASP.NET thread, so only the high level principles are relevant).

Greg
@Greg: the thread you linked is about ASP.NET so it may not be much help.
Alex - Aotea Studios
Oops.I could have sworn that I saw a relatively recent Rails question along those lines, but that obviously isn't it. I guess the point is that the view helper should really be seen as part of the view, and the MVC pattern frowns upon calling the controller from the view. Googling Rails MVC is an exercise left to the OP.
Greg
A: 

You don't call controller-methods from helpers. That is: if you mean a method that collects data and then renders a view (any other method that needs to be called should probably not be in a controller). It is definitely bad practice and breaks MVC.

In Rails, it is possible to call helper methods inside a controller though.

It would be interesting to know why you would see the need to do this.

nathanvda