Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we call a Controller's method from a view (as we call from helper ideally)?

In Rails MVC, can you call a controller's method from a view (as a method could be called call from a helper)? If yes, how?

like image 890
Manish Shrivastava Avatar asked Jan 18 '12 07:01

Manish Shrivastava


People also ask

Can we call controller method from helper?

You generally 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.

Can we call one controller method from another controller?

Yes, you can call a method of another controller. The controller is also a simple class.

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended.


1 Answers

Here is the answer:

class MyController < ApplicationController   def my_method     # Lots of stuff   end   helper_method :my_method end 

Then, in your view, you can reference it in ERB exactly how you expect with <% or <%=:

<% my_method %> 
like image 151
sailor Avatar answered Oct 05 '22 22:10

sailor