Recommendations for calling controller methods in auxiliary modules?

A few questions:

  • Is it possible to call the controller method in an auxiliary module (for example, an application assistant)?

  • If so, how does the helper handle rendering of views? Ignore?

  • In what cases do you want to call the controller method from the helper? Is this a bad practice?

  • Do you have sample code in which you call controller methods in a helper?

+7
ruby-on-rails controller helper
source share
3 answers

Usually you do not call controllers from assistants. That is: if you mean a method that collects data and then displays a view (any other method that needs to be called should probably not be in the controller). This is definitely bad practice and breaks MVC .

Nevertheless, it is quite possible to make controller methods available in views, for example, the current_user method can serve as an example.

To make the controller method available in views as a helper method, simply do

 private def current_user # do something sensible here @current_user ||= session[:user] end helper_method :current_user 

Such a method is best defined in the private section, or it may be available as an action (if you use the template in your routing).

+10
source share

Declare your methods on the appropriate controller

 private def method_name1 ... end def method_name2 ... end 

In the header of the controller, declare

 helper_method :method_name1, :method_name2 

You may want to declare these methods closed.

And what is it, now you can use your method in the helper

+8
source share

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

I will not protect MVC itself (there are many links on the Internet), but this SO thread about calling the controller from the view should start you off.

Calling the controller out of view? (note: this is an ASP.NET stream, so only high-level principles are important).

0
source share

All Articles